repo_name
stringclasses 10
values | file_path
stringlengths 29
222
| content
stringlengths 24
926k
| extention
stringclasses 5
values |
---|---|---|---|
fprime | data/projects/fprime/Drv/StreamCrossover/test/ut/StreamCrossoverTester.cpp | // ======================================================================
// \title StreamCrossover.hpp
// \author ethanchee
// \brief cpp file for StreamCrossover test harness implementation class
// ======================================================================
#include "StreamCrossoverTester.hpp"
namespace Drv {
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
StreamCrossoverTester ::
StreamCrossoverTester() :
StreamCrossoverGTestBase("Tester", StreamCrossoverTester::MAX_HISTORY_SIZE),
component("StreamCrossover")
{
this->initComponents();
this->connectPorts();
}
StreamCrossoverTester ::
~StreamCrossoverTester()
{
}
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
void StreamCrossoverTester ::
sendTestBuffer()
{
U8 testStr[6] = "test\n";
Fw::Buffer sendBuffer(testStr, sizeof(testStr));
this->invoke_to_streamIn(0, sendBuffer, Drv::RecvStatus::RECV_OK);
// Ensure only one buffer was sent to streamOut
ASSERT_from_streamOut_SIZE(1);
// Ensure the sendBuffer was sent
ASSERT_from_streamOut(0, sendBuffer);
}
void StreamCrossoverTester ::
testFail()
{
U8 testStr[6] = "test\n";
Fw::Buffer sendBuffer(testStr, sizeof(testStr));
this->invoke_to_streamIn(0, sendBuffer, Drv::RecvStatus::RECV_ERROR);
// Ensure only one buffer was sent to errorDeallocate port on RECV_ERROR
ASSERT_from_errorDeallocate_SIZE(1);
// Ensure the sendBuffer was sent
ASSERT_from_errorDeallocate(0, sendBuffer);
// Ensure the error event was sent
ASSERT_EVENTS_StreamOutError_SIZE(1);
// Ensure the error is SEND_ERROR
ASSERT_EVENTS_StreamOutError(0, Drv::SendStatus::SEND_ERROR);
}
// ----------------------------------------------------------------------
// Handlers for typed from ports
// ----------------------------------------------------------------------
Drv::SendStatus StreamCrossoverTester ::
from_streamOut_handler(
const NATIVE_INT_TYPE portNum,
Fw::Buffer &sendBuffer
)
{
this->pushFromPortEntry_streamOut(sendBuffer);
U8 testStr[6] = "test\n";
Fw::Buffer cmpBuffer(testStr, sizeof(testStr));
if(!(cmpBuffer == sendBuffer))
{
return Drv::SendStatus::SEND_ERROR;
}
return Drv::SendStatus::SEND_OK;
}
void StreamCrossoverTester ::
from_errorDeallocate_handler(
const NATIVE_INT_TYPE portNum,
Fw::Buffer &fwBuffer
)
{
this->pushFromPortEntry_errorDeallocate(fwBuffer);
}
} // end namespace Drv
| cpp |
fprime | data/projects/fprime/Drv/StreamCrossover/test/ut/StreamCrossoverTester.hpp | // ======================================================================
// \title StreamCrossover/test/ut/Tester.hpp
// \author ethanchee
// \brief hpp file for StreamCrossover test harness implementation class
// ======================================================================
#ifndef TESTER_HPP
#define TESTER_HPP
#include "StreamCrossoverGTestBase.hpp"
#include "Drv/StreamCrossover/StreamCrossover.hpp"
namespace Drv {
class StreamCrossoverTester :
public StreamCrossoverGTestBase
{
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
public:
// Maximum size of histories storing events, telemetry, and port outputs
static const NATIVE_INT_TYPE MAX_HISTORY_SIZE = 10;
// Instance ID supplied to the component instance under test
static const NATIVE_INT_TYPE TEST_INSTANCE_ID = 0;
//! Construct object StreamCrossoverTester
//!
StreamCrossoverTester();
//! Destroy object StreamCrossoverTester
//!
~StreamCrossoverTester();
public:
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
//! Send a test buffer to streamOut from streamIn
//!
void sendTestBuffer();
//! Send a fail RECV_STATUS to test error
//!
void testFail();
private:
// ----------------------------------------------------------------------
// Handlers for typed from ports
// ----------------------------------------------------------------------
//! Handler for from_streamOut
//!
Drv::SendStatus from_streamOut_handler(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::Buffer &sendBuffer
);
//! Handler for from_deallocate
//!
void from_errorDeallocate_handler(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::Buffer &fwBuffer
);
private:
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
//! Connect ports
//!
void connectPorts();
//! Initialize components
//!
void initComponents();
private:
// ----------------------------------------------------------------------
// Variables
// ----------------------------------------------------------------------
//! The component under test
//!
StreamCrossover component;
};
} // end namespace Drv
#endif
| hpp |
fprime | data/projects/fprime/Drv/DataTypes/DataBuffer.cpp | #include <Drv/DataTypes/DataBuffer.hpp>
#include <Fw/Types/Assert.hpp>
namespace Drv {
DataBuffer::DataBuffer(const U8 *args, NATIVE_UINT_TYPE size) {
Fw::SerializeStatus stat = Fw::SerializeBufferBase::setBuff(args,size);
FW_ASSERT(Fw::FW_SERIALIZE_OK == stat,static_cast<NATIVE_INT_TYPE>(stat));
}
DataBuffer::DataBuffer() {
}
DataBuffer::~DataBuffer() {
}
DataBuffer::DataBuffer(const DataBuffer& other) : Fw::SerializeBufferBase() {
Fw::SerializeStatus stat = Fw::SerializeBufferBase::setBuff(other.m_data,other.getBuffLength());
FW_ASSERT(Fw::FW_SERIALIZE_OK == stat,static_cast<NATIVE_INT_TYPE>(stat));
}
DataBuffer& DataBuffer::operator=(const DataBuffer& other) {
if(this == &other) {
return *this;
}
Fw::SerializeStatus stat = Fw::SerializeBufferBase::setBuff(other.m_data,other.getBuffLength());
FW_ASSERT(Fw::FW_SERIALIZE_OK == stat,static_cast<NATIVE_INT_TYPE>(stat));
return *this;
}
NATIVE_UINT_TYPE DataBuffer::getBuffCapacity() const {
return sizeof(this->m_data);
}
const U8* DataBuffer::getBuffAddr() const {
return this->m_data;
}
U8* DataBuffer::getBuffAddr() {
return this->m_data;
}
}
| cpp |
fprime | data/projects/fprime/Drv/DataTypes/DataBuffer.hpp | #ifndef _DrvDataBuffer_hpp_
#define _DrvDataBuffer_hpp_
#include <FpConfig.hpp>
#include <Fw/Types/Serializable.hpp>
namespace Drv {
class DataBuffer : public Fw::SerializeBufferBase {
public:
enum {
DATA_BUFFER_SIZE = 256,
SERIALIZED_TYPE_ID = 1010,
SERIALIZED_SIZE = DATA_BUFFER_SIZE + sizeof(FwBuffSizeType)
};
DataBuffer(const U8 *args, NATIVE_UINT_TYPE size);
DataBuffer();
DataBuffer(const DataBuffer& other);
virtual ~DataBuffer();
DataBuffer& operator=(const DataBuffer& other);
NATIVE_UINT_TYPE getBuffCapacity() const; // !< returns capacity, not current size, of buffer
U8* getBuffAddr();
const U8* getBuffAddr() const;
private:
U8 m_data[DATA_BUFFER_SIZE]; // packet data buffer
};
}
#endif
| hpp |
fprime | data/projects/fprime/Drv/TcpServer/TcpServer.hpp | // ======================================================================
// TcpServer.hpp
// Standardization header for TcpServer
// ======================================================================
#ifndef Drv_TcpServer_HPP
#define Drv_TcpServer_HPP
#include "Drv/TcpServer/TcpServerComponentImpl.hpp"
namespace Drv {
typedef TcpServerComponentImpl TcpServer;
}
#endif
| hpp |
fprime | data/projects/fprime/Drv/TcpServer/TcpServerComponentImpl.cpp | // ======================================================================
// \title TcpServerComponentImpl.cpp
// \author mstarch
// \brief cpp file for TcpServerComponentImpl component implementation class
//
// \copyright
// Copyright 2009-2020, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include <Drv/TcpServer/TcpServerComponentImpl.hpp>
#include <FpConfig.hpp>
#include "Fw/Types/Assert.hpp"
namespace Drv {
// ----------------------------------------------------------------------
// Construction, initialization, and destruction
// ----------------------------------------------------------------------
TcpServerComponentImpl::TcpServerComponentImpl(const char* const compName)
: TcpServerComponentBase(compName),
SocketReadTask() {}
SocketIpStatus TcpServerComponentImpl::configure(const char* hostname,
const U16 port,
const U32 send_timeout_seconds,
const U32 send_timeout_microseconds) {
return m_socket.configure(hostname, port, send_timeout_seconds, send_timeout_microseconds);
}
TcpServerComponentImpl::~TcpServerComponentImpl() {}
// ----------------------------------------------------------------------
// Implementations for socket read task virtual methods
// ----------------------------------------------------------------------
IpSocket& TcpServerComponentImpl::getSocketHandler() {
return m_socket;
}
Fw::Buffer TcpServerComponentImpl::getBuffer() {
return allocate_out(0, 1024);
}
void TcpServerComponentImpl::sendBuffer(Fw::Buffer buffer, SocketIpStatus status) {
Drv::RecvStatus recvStatus = (status == SOCK_SUCCESS) ? RecvStatus::RECV_OK : RecvStatus::RECV_ERROR;
this->recv_out(0, buffer, recvStatus);
}
void TcpServerComponentImpl::connected() {
if (isConnected_ready_OutputPort(0)) {
this->ready_out(0);
}
}
// ----------------------------------------------------------------------
// Handler implementations for user-defined typed input ports
// ----------------------------------------------------------------------
Drv::SendStatus TcpServerComponentImpl::send_handler(const NATIVE_INT_TYPE portNum, Fw::Buffer& fwBuffer) {
Drv::SocketIpStatus status = m_socket.send(fwBuffer.getData(), fwBuffer.getSize());
// Only deallocate buffer when the caller is not asked to retry
if (status == SOCK_INTERRUPTED_TRY_AGAIN) {
return SendStatus::SEND_RETRY;
} else if (status != SOCK_SUCCESS) {
deallocate_out(0, fwBuffer);
return SendStatus::SEND_ERROR;
}
deallocate_out(0, fwBuffer);
return SendStatus::SEND_OK;
}
} // end namespace Drv
| cpp |
fprime | data/projects/fprime/Drv/TcpServer/TcpServerComponentImpl.hpp | // ======================================================================
// \title TcpServerComponentImpl.hpp
// \author mstarch
// \brief hpp file for TcpServerComponentImpl component implementation class
//
// \copyright
// Copyright 2009-2020, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#ifndef TcpServerComponentImpl_HPP
#define TcpServerComponentImpl_HPP
#include <IpCfg.hpp>
#include <Drv/Ip/IpSocket.hpp>
#include <Drv/Ip/SocketReadTask.hpp>
#include <Drv/Ip/TcpServerSocket.hpp>
#include "Drv/TcpServer/TcpServerComponentAc.hpp"
namespace Drv {
class TcpServerComponentImpl : public TcpServerComponentBase, public SocketReadTask {
public:
// ----------------------------------------------------------------------
// Construction, initialization, and destruction
// ----------------------------------------------------------------------
/**
* \brief construct the TcpClient component.
* \param compName: name of this component
*/
TcpServerComponentImpl(const char* const compName);
/**
* \brief Destroy the component
*/
~TcpServerComponentImpl();
// ----------------------------------------------------------------------
// Helper methods to start and stop socket
// ----------------------------------------------------------------------
/**
* \brief Configures the TcpClient settings but does not open the connection
*
* The TcpClientComponent needs to connect to a remote TCP server. This call configures the hostname, port and
* send timeouts for that socket connection. This call should be performed on system startup before recv or send
* are called. Note: hostname must be a dot-notation IP address of the form "x.x.x.x". DNS translation is left up
* to the user.
*
* \param hostname: ip address of remote tcp server in the form x.x.x.x
* \param port: port of remote tcp server
* \param send_timeout_seconds: send timeout seconds component. Defaults to: SOCKET_TIMEOUT_SECONDS
* \param send_timeout_microseconds: send timeout microseconds component. Must be less than 1000000. Defaults to:
* SOCKET_TIMEOUT_MICROSECONDS
* \return status of the configure
*/
SocketIpStatus configure(const char* hostname,
const U16 port,
const U32 send_timeout_seconds = SOCKET_SEND_TIMEOUT_SECONDS,
const U32 send_timeout_microseconds = SOCKET_SEND_TIMEOUT_MICROSECONDS);
PROTECTED:
// ----------------------------------------------------------------------
// Implementations for socket read task virtual methods
// ----------------------------------------------------------------------
/**
* \brief returns a reference to the socket handler
*
* Gets a reference to the current socket handler in order to operate generically on the IpSocket instance. Used for
* receive, and open calls. This socket handler will be a TcpClient.
*
* \return IpSocket reference
*/
IpSocket& getSocketHandler();
/**
* \brief returns a buffer to fill with data
*
* Gets a reference to a buffer to fill with data. This allows the component to determine how to provide a
* buffer and the socket read task just fills said buffer.
*
* \return Fw::Buffer to fill with data
*/
Fw::Buffer getBuffer();
/**
* \brief sends a buffer to be filled with data
*
* Sends the buffer gotten by getBuffer that has now been filled with data. This is used to delegate to the
* component how to send back the buffer. Ignores buffers with error status error.
*
* \return Fw::Buffer filled with data to send out
*/
void sendBuffer(Fw::Buffer buffer, SocketIpStatus status);
/**
* \brief called when the IPv4 system has been connected
*/
void connected();
PRIVATE:
// ----------------------------------------------------------------------
// Handler implementations for user-defined typed input ports
// ----------------------------------------------------------------------
/**
* \brief Send data out of the TcpClient
*
* Passing data to this port will send data from the TcpClient to whatever TCP server this component has connected
* to. Should the socket not be opened or was disconnected, then this port call will return SEND_RETRY and critical
* transmissions should be retried. SEND_ERROR indicates an unresolvable error. SEND_OK is returned when the data
* has been sent.
*
* Note: this component delegates the reopening of the socket to the read thread and thus the caller should retry
* after the read thread has attempted to reopen the port but does not need to reopen the port manually.
*
* \param portNum: fprime port number of the incoming port call
* \param fwBuffer: buffer containing data to be sent
* \return SEND_OK on success, SEND_RETRY when critical data should be retried and SEND_ERROR upon error
*/
Drv::SendStatus send_handler(const NATIVE_INT_TYPE portNum, Fw::Buffer& fwBuffer);
Drv::TcpServerSocket m_socket; //!< Socket implementation
};
} // end namespace Drv
#endif // end TcpServerComponentImpl
| hpp |
fprime | data/projects/fprime/Drv/TcpServer/test/ut/TcpServerTester.hpp | // ======================================================================
// \title TcpServer/test/ut/Tester.hpp
// \author mstarch
// \brief hpp file for ByteStreamDriverModel test harness implementation class
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#ifndef TESTER_HPP
#define TESTER_HPP
#include "TcpServerGTestBase.hpp"
#include "Drv/TcpServer/TcpServerComponentImpl.hpp"
#include "Drv/Ip/TcpClientSocket.hpp"
#define SEND_DATA_BUFFER_SIZE 1024
namespace Drv {
class TcpServerTester :
public TcpServerGTestBase
{
// Maximum size of histories storing events, telemetry, and port outputs
static const NATIVE_INT_TYPE MAX_HISTORY_SIZE = 1000;
// Instance ID supplied to the component instance under test
static const NATIVE_INT_TYPE TEST_INSTANCE_ID = 0;
// Queue depth supplied to component instance under test
static const NATIVE_INT_TYPE TEST_INSTANCE_QUEUE_DEPTH = 100;
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
public:
//! Construct object TcpServerTester
//!
TcpServerTester();
//! Destroy object TcpServerTester
//!
~TcpServerTester();
public:
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
//! Test basic messaging
//!
void test_basic_messaging();
//! Test basic reconnection behavior
//!
void test_multiple_messaging();
//! Test receive via thread
//!
void test_receive_thread();
//! Test advanced (duration) reconnect
//!
void test_advanced_reconnect();
// Helpers
void test_with_loop(U32 iterations, bool recv_thread=false);
private:
// ----------------------------------------------------------------------
// Handlers for typed from ports
// ----------------------------------------------------------------------
//! Handler for from_recv
//!
void from_recv_handler(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::Buffer &recvBuffer,
const RecvStatus &recvStatus
);
//! Handler for from_ready
//!
void from_ready_handler(
const NATIVE_INT_TYPE portNum /*!< The port number*/
);
//! Handler for from_allocate
//!
Fw::Buffer from_allocate_handler(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
U32 size
);
//! Handler for from_deallocate
//!
void from_deallocate_handler(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::Buffer &fwBuffer
);
private:
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
//! Connect ports
//!
void connectPorts();
//! Initialize components
//!
void initComponents();
private:
// ----------------------------------------------------------------------
// Variables
// ----------------------------------------------------------------------
//! The component under test
//!
TcpServerComponentImpl component;
Fw::Buffer m_data_buffer;
Fw::Buffer m_data_buffer2;
U8 m_data_storage[SEND_DATA_BUFFER_SIZE];
std::atomic<bool> m_spinner;
};
} // end namespace Drv
#endif
| hpp |
fprime | data/projects/fprime/Drv/TcpServer/test/ut/TcpServerTestMain.cpp | // ----------------------------------------------------------------------
// TestMain.cpp
// ----------------------------------------------------------------------
#include "TcpServerTester.hpp"
TEST(Nominal, BasicMessaging) {
Drv::TcpServerTester tester;
tester.test_basic_messaging();
}
TEST(Nominal, BasicReceiveThread) {
Drv::TcpServerTester tester;
tester.test_receive_thread();
}
TEST(Reconnect, MultiMessaging) {
Drv::TcpServerTester tester;
tester.test_multiple_messaging();
}
TEST(Reconnect, ReceiveThreadReconnect) {
Drv::TcpServerTester tester;
tester.test_advanced_reconnect();
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| cpp |
fprime | data/projects/fprime/Drv/TcpServer/test/ut/TcpServerTester.cpp | // ======================================================================
// \title TcpServerTester.cpp
// \author mstarch
// \brief cpp file for TcpServerTester for TcpServer
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include "TcpServerTester.hpp"
#include "STest/Pick/Pick.hpp"
#include "Os/Log.hpp"
#include <Drv/Ip/test/ut/PortSelector.hpp>
#include <Drv/Ip/test/ut/SocketTestHelper.hpp>
Os::Log logger;
namespace Drv {
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
void TcpServerTester ::test_with_loop(U32 iterations, bool recv_thread) {
U8 buffer[sizeof(m_data_storage)] = {};
Drv::SocketIpStatus status1 = Drv::SOCK_SUCCESS;
Drv::SocketIpStatus status2 = Drv::SOCK_SUCCESS;
Drv::SocketIpStatus serverStat = Drv::SOCK_SUCCESS;
U16 port = Drv::Test::get_free_port();
ASSERT_NE(0, port);
this->component.configure("127.0.0.1", port, 0, 100);
// Start up a receive thread
if (recv_thread) {
Os::TaskString name("receiver thread");
this->component.startSocketTask(name, true, Os::Task::TASK_DEFAULT, Os::Task::TASK_DEFAULT);
EXPECT_TRUE(Drv::Test::wait_on_started(this->component.getSocketHandler(), true, SOCKET_RETRY_INTERVAL_MS/10 + 1));
} else {
serverStat = this->component.startup();
EXPECT_EQ(serverStat, SOCK_SUCCESS);
}
EXPECT_TRUE(component.getSocketHandler().isStarted());
// Loop through a bunch of client disconnects
for (U32 i = 0; i < iterations && serverStat == SOCK_SUCCESS; i++) {
Drv::TcpClientSocket client;
client.configure("127.0.0.1", port, 0, 100);
status2 = client.open();
I32 size = sizeof(m_data_storage);
// Not testing with reconnect thread, we will need to open ourselves
if (not recv_thread) {
status1 = this->component.open();
} else {
EXPECT_TRUE(Drv::Test::wait_on_change(this->component.getSocketHandler(), true, SOCKET_RETRY_INTERVAL_MS/10 + 1));
}
EXPECT_TRUE(this->component.getSocketHandler().isOpened());
EXPECT_EQ(status1, Drv::SOCK_SUCCESS);
EXPECT_EQ(status2, Drv::SOCK_SUCCESS);
// If all the opens worked, then run this
if ((Drv::SOCK_SUCCESS == status1) && (Drv::SOCK_SUCCESS == status2) &&
(this->component.getSocketHandler().isOpened())) {
// Force the sockets not to hang, if at all possible
Drv::Test::force_recv_timeout(this->component.getSocketHandler());
Drv::Test::force_recv_timeout(client);
m_data_buffer.setSize(sizeof(m_data_storage));
Drv::Test::fill_random_buffer(m_data_buffer);
Drv::SendStatus status = invoke_to_send(0, m_data_buffer);
EXPECT_EQ(status, SendStatus::SEND_OK);
status2 = client.recv(buffer, size);
EXPECT_EQ(status2, Drv::SOCK_SUCCESS);
EXPECT_EQ(size, m_data_buffer.getSize());
Drv::Test::validate_random_buffer(m_data_buffer, buffer);
// If receive thread is live, try the other way
if (recv_thread) {
m_spinner = false;
m_data_buffer.setSize(sizeof(m_data_storage));
client.send(m_data_buffer.getData(), m_data_buffer.getSize());
while (not m_spinner) {}
}
}
client.close(); // Client must be closed first or the server risks binding to an existing address
// Properly stop the client on the last iteration
if ((1 + i) == iterations && recv_thread) {
this->component.shutdown();
this->component.stopSocketTask();
this->component.joinSocketTask(nullptr);
} else {
this->component.close();
}
}
ASSERT_from_ready_SIZE(iterations);
}
TcpServerTester ::TcpServerTester()
: TcpServerGTestBase("Tester", MAX_HISTORY_SIZE),
component("TcpServer"),
m_data_buffer(m_data_storage, 0), m_spinner(true) {
this->initComponents();
this->connectPorts();
::memset(m_data_storage, 0, sizeof(m_data_storage));
}
TcpServerTester ::~TcpServerTester() {}
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
void TcpServerTester ::test_basic_messaging() {
test_with_loop(1);
}
void TcpServerTester ::test_multiple_messaging() {
test_with_loop(100);
}
void TcpServerTester ::test_receive_thread() {
test_with_loop(1, true);
}
void TcpServerTester ::test_advanced_reconnect() {
test_with_loop(10, true); // Up to 10 * RECONNECT_MS
}
// ----------------------------------------------------------------------
// Handlers for typed from ports
// ----------------------------------------------------------------------
void TcpServerTester ::from_recv_handler(const NATIVE_INT_TYPE portNum, Fw::Buffer& recvBuffer, const RecvStatus& recvStatus) {
this->pushFromPortEntry_recv(recvBuffer, recvStatus);
// Make sure we can get to unblocking the spinner
EXPECT_EQ(m_data_buffer.getSize(), recvBuffer.getSize()) << "Invalid transmission size";
Drv::Test::validate_random_buffer(m_data_buffer, recvBuffer.getData());
m_spinner = true;
delete[] recvBuffer.getData();
}
void TcpServerTester ::from_ready_handler(const NATIVE_INT_TYPE portNum) {
this->pushFromPortEntry_ready();
}
Fw::Buffer TcpServerTester ::
from_allocate_handler(
const NATIVE_INT_TYPE portNum,
U32 size
)
{
this->pushFromPortEntry_allocate(size);
Fw::Buffer buffer(new U8[size], size);
m_data_buffer2 = buffer;
return buffer;
}
void TcpServerTester ::
from_deallocate_handler(
const NATIVE_INT_TYPE portNum,
Fw::Buffer &fwBuffer
)
{
this->pushFromPortEntry_deallocate(fwBuffer);
}
} // end namespace Drv
| cpp |
fprime | data/projects/fprime/config/TlmChanImplCfg.hpp | /**
* \file
* \author T. Canham
* \brief Configuration file for Telemetry Channel component
*
* \copyright
* Copyright 2009-2015, by the California Institute of Technology.
* ALL RIGHTS RESERVED. United States Government Sponsorship
* acknowledged.
* <br /><br />
*/
#ifndef TLMCHANIMPLCFG_HPP_
#define TLMCHANIMPLCFG_HPP_
// Anonymous namespace for configuration parameters
// The parameters below provide for tuning of the hash function used to
// write and read entries in the database. The has function is very simple;
// It first takes the telemetry ID and does a modulo computation with
// TLMCHAN_HASH_MOD_VALUE. It then does a second modulo with the number
// of slots to make sure the value lands in the provided slots.
// The values can be experimented with to try and balance the number
// of slots versus the number of buckets.
// To test the set of telemetry ID in the system to see if the hash is
// balanced, do the following:
// 1) From the deployment directory (e.g Ref), do a full build then type:
// "make comp_report_gen"
// This will generate a list in "<deployment dir>/ComponentReport.txt"
// with all the telemetry IDs in the deployment.
// 2) Cut and paste the ID list to the array declared in the TlmChan unit test
// file TelemChanImplTester.cpp in the runMultiChannel() method.
// 3) Run the unit test ("make ut run_ut")
// 4) After writing all the telemetry IDs to the component, the
// unit test will dump the hash table. The output looks like the following:
// Slot: <n> - slot number
// Entry - a bucket assigned to the slot
// ... (Other buckets in the slot)
// The number of buckets assigned to each slot can be checked for balance.
namespace {
enum {
TLMCHAN_NUM_TLM_HASH_SLOTS = 15, // !< Number of slots in the hash table.
// Works best when set to about twice the number of components producing telemetry
TLMCHAN_HASH_MOD_VALUE = 99, // !< The modulo value of the hashing function.
// Should be set to a little below the ID gaps to spread the entries around
TLMCHAN_HASH_BUCKETS = 50 // !< Buckets assignable to a hash slot.
// Buckets must be >= number of telemetry channels in system
};
}
#endif /* TLMCHANIMPLCFG_HPP_ */
| hpp |
fprime | data/projects/fprime/config/ActiveRateGroupCfg.hpp | /*
* \author: Tim Canham
* \file:
* \brief
*
* This file has configuration settings for the ActiveRateGroup component.
*
*
* Copyright 2014-2015, by the California Institute of Technology.
* ALL RIGHTS RESERVED. United States Government Sponsorship
* acknowledged.
*
*/
#ifndef ACTIVERATEGROUP_ACTIVERATEGROUPCFG_HPP_
#define ACTIVERATEGROUP_ACTIVERATEGROUPCFG_HPP_
namespace Svc {
enum {
//! Number of overruns allowed before overrun event is throttled
ACTIVE_RATE_GROUP_OVERRUN_THROTTLE = 5,
};
}
#endif /* ACTIVERATEGROUP_ACTIVERATEGROUPCFG_HPP_ */
| hpp |
fprime | data/projects/fprime/config/StaticMemoryConfig.hpp | /*
* StaticMemoryCfg.hpp:
*
* Configuration settings for the static memory component.
*/
#ifndef SVC_STATIC_MEMORY_CFG_HPP_
#define SVC_STATIC_MEMORY_CFG_HPP_
namespace Svc {
enum StaticMemoryConfig {
STATIC_MEMORY_ALLOCATION_SIZE = 2048
};
}
#endif
| hpp |
fprime | data/projects/fprime/config/UdpSenderComponentImplCfg.hpp | /*
* UdpSenderComponentImplCfg.hpp
*
* Created on: Nov 11, 2017
* Author: tim
*/
#ifndef SVC_UDPSENDER_UDPSENDERCOMPONENTIMPLCFG_HPP_
#define SVC_UDPSENDER_UDPSENDERCOMPONENTIMPLCFG_HPP_
#include <FpConfig.hpp>
namespace Svc {
static const NATIVE_UINT_TYPE UDP_SENDER_MSG_SIZE = 256;
}
#endif /* SVC_UDPSENDER_UDPSENDERCOMPONENTIMPLCFG_HPP_ */
| hpp |
fprime | data/projects/fprime/config/PrmDbImplCfg.hpp | /*
* PrmDblImplCfg.hpp
*
* Created on: Mar 13, 2015
* Author: tcanham
*/
#ifndef PRMDB_PRMDBLIMPLCFG_HPP_
#define PRMDB_PRMDBLIMPLCFG_HPP_
// Anonymous namespace for configuration parameters
namespace {
enum {
PRMDB_NUM_DB_ENTRIES = 25, // !< Number of entries in the parameter database
PRMDB_ENTRY_DELIMITER = 0xA5 // !< Byte value that should precede each parameter in file; sanity check against file integrity. Should match ground system.
};
}
#endif /* PRMDB_PRMDBLIMPLCFG_HPP_ */
| hpp |
fprime | data/projects/fprime/config/IpCfg.hpp | // ======================================================================
// \title IpCfg.hpp
// \author mstarch
// \brief hpp file for SocketIpDriver component implementation class
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#ifndef REF_IPCFG_HPP
#define REF_IPCFG_HPP
enum IpCfg {
SOCKET_SEND_TIMEOUT_SECONDS = 1, // Seconds component of timeout to an individual send
SOCKET_SEND_TIMEOUT_MICROSECONDS = 0, // Milliseconds component of timeout to an individual send
SOCKET_IP_SEND_FLAGS = 0, // send, sendto FLAGS argument
SOCKET_IP_RECV_FLAGS = 0, // recv FLAGS argument
SOCKET_MAX_ITERATIONS = 0xFFFF, // Maximum send/recv attempts before an error is returned
SOCKET_RETRY_INTERVAL_MS = 1000, // Interval between connection retries before main recv thread starts
SOCKET_MAX_HOSTNAME_SIZE = 256 // Maximum stored hostname
};
#endif //REF_IPCFG_HPP
| hpp |
fprime | data/projects/fprime/config/FpConfig.h | /**
* \file: FpConfig.h
* \author T. Canham, mstarch
* \brief C-compatible configuration header for fprime configuration
*
* \copyright
* Copyright 2009-2015, by the California Institute of Technology.
* ALL RIGHTS RESERVED. United States Government Sponsorship
* acknowledged.
*/
#include <Fw/Types/BasicTypes.h>
#ifndef FPCONFIG_H_
#define FPCONFIG_H_
// ----------------------------------------------------------------------
// Type aliases
// ----------------------------------------------------------------------
// The type of port indices and smaller sizes internal to the software
typedef PlatformIndexType FwIndexType;
#define PRI_FwIndexType PRI_PlatformIndexType
// The signed type of larger sizes internal to the software, e.g., memory buffer sizes,
// file sizes
typedef PlatformSignedSizeType FwSignedSizeType;
#define PRI_FwSignedSizeType PRI_PlatformSignedSizeType
// The unsigned type of larger sizes internal to the software, e.g., memory buffer sizes,
// file sizes
typedef PlatformSizeType FwSizeType;
#define PRI_FwSizeType PRI_PlatformSizeType
// The type of an assertion argument
typedef PlatformAssertArgType FwAssertArgType;
#define PRI_FwAssertArgType PRI_PlatformAssertArgType
// The type of a machine integer. Ordinarily this should be int.
typedef PlatformIntType FwNativeIntType;
#define PRI_FwNativeIntType PRI_PlatformIntType
// The type of a machine unsigned integer. Ordinarily this should be unsigned int.
typedef PlatformUIntType FwNativeUIntType;
#define PRI_FwNativeUIntType PRI_PlatformUIntType
// The type used to serialize a size value
typedef U16 FwSizeStoreType;
#define PRI_FwSizeStoreType PRIu16
// The type used to serialize a C++ enumeration constant
// FPP enumerations are serialized according to their representation types
typedef I32 FwEnumStoreType;
#define PRI_FwEnumStoreType PRId32
// Define enumeration for Time base types
// Note: maintaining C-style
typedef enum {
TB_NONE, //!< No time base has been established
TB_PROC_TIME, //!< Indicates time is processor cycle time. Not tied to external time
TB_WORKSTATION_TIME, //!< Time as reported on workstation where software is running. For testing.
TB_DONT_CARE =
0xFFFF //!< Don't care value for sequences. If FwTimeBaseStoreType is changed, value should be changed
} TimeBase;
#define FW_CONTEXT_DONT_CARE 0xFF //!< Don't care value for time contexts in sequences
// The type used to serialize a time base value
typedef U16 FwTimeBaseStoreType;
#define PRI_FwTimeBaseStoreType PRIu16
// The type used to serialize a time context value
typedef U8 FwTimeContextStoreType;
#define PRI_FwTimeContextStoreType PRIu8
// The type of a com packet descriptor
typedef U32 FwPacketDescriptorType;
#define PRI_FwPacketDescriptorType PRIu32
// The type of a command opcode
typedef U32 FwOpcodeType;
#define PRI_FwOpcodeType PRIu32
// The type of a telemetry channel identifier
typedef U32 FwChanIdType;
#define PRI_FwChanIdType PRIu32
// The type of an event identifier
typedef U32 FwEventIdType;
#define PRI_FwEventIdType PRIu32
// The type of a parameter identifier
typedef U32 FwPrmIdType;
#define PRI_FwPrmIdType PRIu32
// The type of a telemetry packet identifier
typedef U16 FwTlmPacketizeIdType;
#define PRI_FwTlmPacketizeIdType PRIu16
// The type of a queue priority
typedef I32 FwQueuePriorityType;
#define PRI_FwQueuePriorityType PRId32
// The type of a data product identifier
typedef U32 FwDpIdType;
#define PRI_FwDpIdType PRIu32
// The type of a data product priority
typedef U32 FwDpPriorityType;
#define PRI_FwDpPriorityType PRIu32
// ----------------------------------------------------------------------
// Derived type aliases
// By default, these types are aliases of types defined above
// If necessary, you can change these definitions
// In most cases, the defaults should work
// ----------------------------------------------------------------------
// The type of a queue size
typedef FwIndexType FwQueueSizeType;
#define PRI_FwQueueSizeType PRI_FwIndexType
// ----------------------------------------------------------------------
// Configuration switches
// ----------------------------------------------------------------------
// Boolean values for serialization
#ifndef FW_SERIALIZE_TRUE_VALUE
#define FW_SERIALIZE_TRUE_VALUE (0xFF) //!< Value encoded during serialization for boolean true
#endif
#ifndef FW_SERIALIZE_FALSE_VALUE
#define FW_SERIALIZE_FALSE_VALUE (0x00) //!< Value encoded during serialization for boolean false
#endif
// Allow objects to have names. Allocates storage for each instance
#ifndef FW_OBJECT_NAMES
#define FW_OBJECT_NAMES \
1 //!< Indicates whether or not object names are stored (more memory, can be used for tracking objects)
#endif
// To reduce binary size, FW_OPTIONAL_NAME(<string>) can be used to substitute strings with an empty string
// when running with FW_OBJECT_NAMES disabled
#if FW_OBJECT_NAMES == 1
#define FW_OPTIONAL_NAME(name) name
#else
#define FW_OPTIONAL_NAME(name) ""
#endif
// Add methods to query an object about its name. Can be overridden by derived classes
// For FW_OBJECT_TO_STRING to work, FW_OBJECT_NAMES must be enabled
#if FW_OBJECT_NAMES == 1
#ifndef FW_OBJECT_TO_STRING
#define FW_OBJECT_TO_STRING \
1 //!< Indicates whether or not generated objects have toString() methods to dump internals (more code)
#endif
#else
#define FW_OBJECT_TO_STRING 0
#endif
// Adds the ability for all component related objects to register
// centrally.
#ifndef FW_OBJECT_REGISTRATION
#define FW_OBJECT_REGISTRATION \
1 //!< Indicates whether or not objects can register themselves (more code, more object tracking)
#endif
#ifndef FW_QUEUE_REGISTRATION
#define FW_QUEUE_REGISTRATION 1 //!< Indicates whether or not queue registration is used
#endif
#ifndef FW_BAREMETAL_SCHEDULER
#define FW_BAREMETAL_SCHEDULER \
0 //!< Indicates whether or not a baremetal scheduler should be used. Alternatively the Os scheduler is used.
#endif
// Port Facilities
// This allows tracing calls through ports for debugging
#ifndef FW_PORT_TRACING
#define FW_PORT_TRACING 1 //!< Indicates whether port calls are traced (more code, more visibility into execution)
#endif
// This generates code to connect to serialized ports
#ifndef FW_PORT_SERIALIZATION
#define FW_PORT_SERIALIZATION \
1 //!< Indicates whether there is code in ports to serialize the call (more code, but ability to serialize calls
//!< for multi-note systems)
#endif
// Component Facilities
// Serialization
// Add a type id when serialization is done. More storage,
// but better detection of errors
// TODO: Not working yet
#ifndef FW_SERIALIZATION_TYPE_ID
#define FW_SERIALIZATION_TYPE_ID \
0 //!< Indicates if type id is stored when type is serialized. (More storage, but more type safety)
#endif
// Number of bytes to use for serialization IDs. More
// bytes is more storage, but greater number of IDs
#if FW_SERIALIZATION_TYPE_ID
#ifndef FW_SERIALIZATION_TYPE_ID_BYTES
#define FW_SERIALIZATION_TYPE_ID_BYTES 4 //!< Number of bytes used to represent type id - more bytes, more ids
#endif
#endif
// Set assertion form. Options:
// 1. FW_NO_ASSERT: assertions are compiled out, side effects are kept
// 2. FW_FILEID_ASSERT: asserts report a file CRC and line number
// 3. FW_FILENAME_ASSERT: asserts report a file path (__FILE__) and line number
// 4. FW_RELATIVE_PATH_ASSERT: asserts report a relative path within F´ or F´ library and line number
//
// Note: users who want alternate asserts should set assert level to FW_NO_ASSERT and define FW_ASSERT in this header
#define FW_ASSERT_DFL_MSG_LEN 256 //!< Maximum assert message length when using the default assert handler
#ifndef FW_ASSERT_LEVEL
#define FW_ASSERT_LEVEL FW_FILENAME_ASSERT //!< Defines the type of assert used
#endif
// Define max length of assert string
#ifndef FW_ASSERT_TEXT_SIZE
#define FW_ASSERT_TEXT_SIZE 120 //!< Size of string used to store assert description
#endif
// Adjust various configuration parameters in the architecture. Some of the above enables may disable some of the values
// The size of the object name stored in the object base class. Larger names will be truncated.
#if FW_OBJECT_NAMES
#ifndef FW_OBJ_NAME_MAX_SIZE
#define FW_OBJ_NAME_MAX_SIZE \
80 //!< Size of object name (if object names enabled). AC Limits to 80, truncation occurs above 80.
#endif
#endif
// When querying an object as to an object-specific description, this specifies the size of the buffer to store the
// description.
#if FW_OBJECT_TO_STRING
#ifndef FW_OBJ_TO_STRING_BUFFER_SIZE
#define FW_OBJ_TO_STRING_BUFFER_SIZE 255 //!< Size of string storing toString() text
#endif
#endif
#if FW_OBJECT_REGISTRATION
// For the simple object registry provided with the framework, this specifies how many objects the registry will store.
#ifndef FW_OBJ_SIMPLE_REG_ENTRIES
#define FW_OBJ_SIMPLE_REG_ENTRIES 500 //!< Number of objects stored in simple object registry
#endif
// When dumping the contents of the registry, this specifies the size of the buffer used to store object names. Should
// be >= FW_OBJ_NAME_MAX_SIZE.
#ifndef FW_OBJ_SIMPLE_REG_BUFF_SIZE
#define FW_OBJ_SIMPLE_REG_BUFF_SIZE 255 //!< Size of object registry dump string
#endif
#endif
#if FW_QUEUE_REGISTRATION
// For the simple queue registry provided with the framework, this specifies how many queues the registry will store.
#ifndef FW_QUEUE_SIMPLE_QUEUE_ENTRIES
#define FW_QUEUE_SIMPLE_QUEUE_ENTRIES 100 //!< Number of queues stored in simple queue registry
#endif
#endif
// Specifies the size of the string holding the queue name for queues
#ifndef FW_QUEUE_NAME_MAX_SIZE
#define FW_QUEUE_NAME_MAX_SIZE 80 //!< Max size of message queue name
#endif
// Specifies the size of the string holding the task name for active components and tasks
#ifndef FW_TASK_NAME_MAX_SIZE
#define FW_TASK_NAME_MAX_SIZE 80 //!< Max size of task name
#endif
// Specifies the size of the buffer that contains a communications packet.
#ifndef FW_COM_BUFFER_MAX_SIZE
#define FW_COM_BUFFER_MAX_SIZE 128 //!< Max size of Fw::Com buffer
#endif
// Specifies the size of the buffer that contains the serialized command arguments.
#ifndef FW_CMD_ARG_BUFFER_MAX_SIZE
#define FW_CMD_ARG_BUFFER_MAX_SIZE (FW_COM_BUFFER_MAX_SIZE - sizeof(FwOpcodeType) - sizeof(FwPacketDescriptorType))
#endif
// Specifies the maximum size of a string in a command argument
#ifndef FW_CMD_STRING_MAX_SIZE
#define FW_CMD_STRING_MAX_SIZE 40 //!< Max character size of command string arguments
#endif
// Normally when a command is deserialized, the handler checks to see if there are any leftover
// bytes in the buffer. If there are, it assumes that the command was corrupted somehow since
// the serialized size should match the serialized size of the argument list. In some cases,
// command buffers are padded so the data can be larger than the serialized size of the command.
// Setting the below to zero will disable the check at the cost of not detecting commands that
// are too large.
#ifndef FW_CMD_CHECK_RESIDUAL
#define FW_CMD_CHECK_RESIDUAL 1 //!< Check for leftover command bytes
#endif
// Specifies the size of the buffer that contains the serialized log arguments.
#ifndef FW_LOG_BUFFER_MAX_SIZE
#define FW_LOG_BUFFER_MAX_SIZE (FW_COM_BUFFER_MAX_SIZE - sizeof(FwEventIdType) - sizeof(FwPacketDescriptorType))
#endif
// Specifies the maximum size of a string in a log event
#ifndef FW_LOG_STRING_MAX_SIZE
#define FW_LOG_STRING_MAX_SIZE 100 //!< Max size of log string parameter type
#endif
// Specifies the size of the buffer that contains the serialized telemetry value.
#ifndef FW_TLM_BUFFER_MAX_SIZE
#define FW_TLM_BUFFER_MAX_SIZE (FW_COM_BUFFER_MAX_SIZE - sizeof(FwChanIdType) - sizeof(FwPacketDescriptorType))
#endif
// Specifies the maximum size of a string in a telemetry channel
#ifndef FW_TLM_STRING_MAX_SIZE
#define FW_TLM_STRING_MAX_SIZE 40 //!< Max size of channelized telemetry string type
#endif
// Specifies the size of the buffer that contains the serialized parameter value.
#ifndef FW_PARAM_BUFFER_MAX_SIZE
#define FW_PARAM_BUFFER_MAX_SIZE (FW_COM_BUFFER_MAX_SIZE - sizeof(FwPrmIdType) - sizeof(FwPacketDescriptorType))
#endif
// Specifies the maximum size of a string in a parameter
#ifndef FW_PARAM_STRING_MAX_SIZE
#define FW_PARAM_STRING_MAX_SIZE 40 //!< Max size of parameter string type
#endif
// Specifies the maximum size of a file upload chunk
#ifndef FW_FILE_BUFFER_MAX_SIZE
#define FW_FILE_BUFFER_MAX_SIZE 255 //!< Max size of file buffer (i.e. chunk of file)
#endif
// Specifies the maximum size of a string in an interface call
#ifndef FW_INTERNAL_INTERFACE_STRING_MAX_SIZE
#define FW_INTERNAL_INTERFACE_STRING_MAX_SIZE 256 //!< Max size of interface string parameter type
#endif
// enables text logging of events as well as data logging. Adds a second logging port for text output.
#ifndef FW_ENABLE_TEXT_LOGGING
#define FW_ENABLE_TEXT_LOGGING 1 //!< Indicates whether text logging is turned on
#endif
// Define the size of the text log string buffer. Should be large enough for format string and arguments
#ifndef FW_LOG_TEXT_BUFFER_SIZE
#define FW_LOG_TEXT_BUFFER_SIZE 256 //!< Max size of string for text log message
#endif
// Define if serializables have toString() method. Turning off will save code space and
// string constants. Must be enabled if text logging enabled
#ifndef FW_SERIALIZABLE_TO_STRING
#define FW_SERIALIZABLE_TO_STRING 1 //!< Indicates if autocoded serializables have toString() methods
#endif
#if FW_SERIALIZABLE_TO_STRING
#ifndef FW_SERIALIZABLE_TO_STRING_BUFFER_SIZE
#define FW_SERIALIZABLE_TO_STRING_BUFFER_SIZE 255 //!< Size of string to store toString() string output
#endif
#endif
// Define if arrays have toString() method.
#ifndef FW_ARRAY_TO_STRING
#define FW_ARRAY_TO_STRING 1 //!< Indicates if autocoded arrays have toString() methods
#endif
#if FW_ARRAY_TO_STRING
#ifndef FW_ARRAY_TO_STRING_BUFFER_SIZE
#define FW_ARRAY_TO_STRING_BUFFER_SIZE 256 //!< Size of string to store toString() string output
#endif
#endif
// Some settings to enable AMPCS compatibility. This breaks regular ISF GUI compatibility
#ifndef FW_AMPCS_COMPATIBLE
#define FW_AMPCS_COMPATIBLE 0 //!< Whether or not JPL AMPCS ground system support is enabled.
#endif
// These settings configure whether or not the timebase and context values for the Fw::Time
// class are used. Some systems may not use or need those fields
#ifndef FW_USE_TIME_BASE
#define FW_USE_TIME_BASE 1 //!< Whether or not to use the time base
#endif
#ifndef FW_USE_TIME_CONTEXT
#define FW_USE_TIME_CONTEXT 1 //!< Whether or not to serialize the time context
#endif
//
// These defines used for the FilepathCharString type
#ifndef FW_FIXED_LENGTH_STRING_SIZE
#define FW_FIXED_LENGTH_STRING_SIZE 256 //!< Character array size for the filepath character type
#endif
#ifndef FW_HANDLE_MAX_SIZE
#define FW_HANDLE_MAX_SIZE 16 //!< Maximum size of a handle for OS resources (files, queues, locks, etc.)
#endif
#ifndef FW_HANDLE_ALIGNMENT
#define FW_HANDLE_ALIGNMENT 16 //!< Alignment of handle storage
#endif
#ifndef FW_FILE_CHUNK_SIZE
#define FW_FILE_CHUNK_SIZE 512 //!< Chunk size for working with files
#endif
// *** NOTE configuration checks are in Fw/Cfg/ConfigCheck.cpp in order to have
// the type definitions in Fw/Types/BasicTypes available.
// DO NOT TOUCH. These types are specified for backwards naming compatibility.
typedef FwSizeStoreType FwBuffSizeType;
#define PRI_FwBuffSizeType PRI_FwSizeStoreType
#endif
| h |
fprime | data/projects/fprime/config/DeframerCfg.hpp | // ======================================================================
// DeframerCfg.hpp
// Configuration settings for Deframer component
// Author: bocchino
// ======================================================================
#ifndef SVC_DEFRAMER_CFG_HPP
#define SVC_DEFRAMER_CFG_HPP
#include <FpConfig.hpp>
namespace Svc {
namespace DeframerCfg {
//! The size of the circular buffer in bytes
static const U32 RING_BUFFER_SIZE = 1024;
//! The size of the polling buffer in bytes
static const U32 POLL_BUFFER_SIZE = 1024;
}
}
#endif
| hpp |
fprime | data/projects/fprime/config/PrmDbImplTesterCfg.hpp | /*
* PrmDbImplTesterCfg.hpp
*
* Created on: Sep 30, 2015
* Author: tcanham
*/
#ifndef PRMDB_TEST_UT_PRMDBIMPLTESTERCFG_HPP_
#define PRMDB_TEST_UT_PRMDBIMPLTESTERCFG_HPP_
enum {
PRMDB_IMPL_TESTER_MAX_READ_BUFFER = 256
};
#endif /* PRMDB_TEST_UT_PRMDBIMPLTESTERCFG_HPP_ */
| hpp |
fprime | data/projects/fprime/config/UdpReceiverComponentImplCfg.hpp | /*
* UdpReceiverComponentImplCfg.hpp
*
* Created on: Nov 11, 2017
* Author: tim
*/
#ifndef SVC_UDPRECEIVER_UDPRECEIVERCOMPONENTIMPLCFG_HPP_
#define SVC_UDPRECEIVER_UDPRECEIVERCOMPONENTIMPLCFG_HPP_
#include <FpConfig.hpp>
namespace Svc {
static const NATIVE_UINT_TYPE UDP_RECEIVER_MSG_SIZE = 256;
}
#endif /* SVC_UDPRECEIVER_UDPRECEIVERCOMPONENTIMPLCFG_HPP_ */
| hpp |
fprime | data/projects/fprime/config/ActiveLoggerImplCfg.hpp | /*
* ActiveLoggerImplCfg.hpp
*
* Created on: Apr 16, 2015
* Author: tcanham
*/
#ifndef ACTIVELOGGER_ACTIVELOGGERIMPLCFG_HPP_
#define ACTIVELOGGER_ACTIVELOGGERIMPLCFG_HPP_
// set default filters
enum {
FILTER_WARNING_HI_DEFAULT = true, //!< WARNING HI events are filtered at input
FILTER_WARNING_LO_DEFAULT = true, //!< WARNING LO events are filtered at input
FILTER_COMMAND_DEFAULT = true, //!< COMMAND events are filtered at input
FILTER_ACTIVITY_HI_DEFAULT = true, //!< ACTIVITY HI events are filtered at input
FILTER_ACTIVITY_LO_DEFAULT = true, //!< ACTIVITY LO events are filtered at input
FILTER_DIAGNOSTIC_DEFAULT = false, //!< DIAGNOSTIC events are filtered at input
};
enum {
TELEM_ID_FILTER_SIZE = 25, //!< Size of telemetry ID filter
};
#endif /* ACTIVELOGGER_ACTIVELOGGERIMPLCFG_HPP_ */
| hpp |
fprime | data/projects/fprime/config/FpConfig.hpp | /**
* \file: FpConfig.hpp
* \author T. Canham, mstarch
* \brief C++-compatible configuration header for fprime configuration
*
* \copyright
* Copyright 2009-2015, by the California Institute of Technology.
* ALL RIGHTS RESERVED. United States Government Sponsorship
* acknowledged.
*/
#include <Fw/Types/BasicTypes.hpp>
extern "C" {
#include <FpConfig.h>
}
| hpp |
fprime | data/projects/fprime/config/BufferManagerComponentImplCfg.hpp | #ifndef __BUFFERMANAGERCOMPONENTIMPLCFG_HPP__
#define __BUFFERMANAGERCOMPONENTIMPLCFG_HPP__
#include <FpConfig.hpp>
namespace Svc {
static const NATIVE_UINT_TYPE BUFFERMGR_MAX_NUM_BINS = 10;
}
#endif // __BUFFERMANAGERCOMPONENTIMPLCFG_HPP__ | hpp |
fprime | data/projects/fprime/config/FileDownlinkCfg.hpp | /*
* FileDownlinkCfg.hpp:
*
* Configuration settings for file downlink component.
*/
#ifndef SVC_FILEDOWNLINK_FILEDOWNLINKCFG_HPP_
#define SVC_FILEDOWNLINK_FILEDOWNLINKCFG_HPP_
#include <FpConfig.hpp>
namespace Svc {
// If this is set to true, the run handler will look to
// see if a packet is ready. If it is false, the next packet
// will be sent as soon as the previous is complete.
static const bool FILEDOWNLINK_PACKETS_BY_RUN = false;
// If this is set, errors that would cause FileDownlink to return an error response, such as a
// missing file or attempting to send a partial chunk past the end of the file will instead
// return success. This is recommended to avoid a non-serious FileDownlink error aborting a
// sequence early. These errors will still be logged as events.
static const bool FILEDOWNLINK_COMMAND_FAILURES_DISABLED = true;
// Size of the internal file downlink buffer. This must now be static as
// file down maintains its own internal buffer.
static const U32 FILEDOWNLINK_INTERNAL_BUFFER_SIZE = FW_COM_BUFFER_MAX_SIZE-sizeof(FwPacketDescriptorType);
}
#endif /* SVC_FILEDOWNLINK_FILEDOWNLINKCFG_HPP_ */
| hpp |
fprime | data/projects/fprime/config/TlmPacketizerCfg.hpp | /*
* TlmPacketizerComponentImplCfg.hpp
*
* Created on: Dec 10, 2017
* Author: tim
*/
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
#ifndef SVC_TLMPACKETIZER_TLMPACKETIZERCOMPONENTIMPLCFG_HPP_
#define SVC_TLMPACKETIZER_TLMPACKETIZERCOMPONENTIMPLCFG_HPP_
#include <FpConfig.hpp>
namespace Svc {
static const NATIVE_UINT_TYPE MAX_PACKETIZER_PACKETS = 200;
static const NATIVE_UINT_TYPE TLMPACKETIZER_NUM_TLM_HASH_SLOTS =
15; // !< Number of slots in the hash table.
// Works best when set to about twice the number of components producing telemetry
static const NATIVE_UINT_TYPE TLMPACKETIZER_HASH_MOD_VALUE =
99; // !< The modulo value of the hashing function.
// Should be set to a little below the ID gaps to spread the entries around
static const NATIVE_UINT_TYPE TLMPACKETIZER_HASH_BUCKETS =
1000; // !< Buckets assignable to a hash slot.
// Buckets must be >= number of telemetry channels in system
static const NATIVE_UINT_TYPE TLMPACKETIZER_MAX_MISSING_TLM_CHECK =
25; // !< Maximum number of missing telemetry channel checks
// packet update mode
enum PacketUpdateMode {
PACKET_UPDATE_ALWAYS, // Always send packets, even if no changes to channel data
PACKET_UPDATE_ON_CHANGE, // Only send packets if any of the channels updates
PACKET_UPDATE_AFTER_FIRST_CHANGE, // Always send packets, but only after first channel has been updated
};
static const PacketUpdateMode PACKET_UPDATE_MODE = PACKET_UPDATE_ON_CHANGE;
} // namespace Svc
#endif /* SVC_TLMPACKETIZER_TLMPACKETIZERCOMPONENTIMPLCFG_HPP_ */
| hpp |
fprime | data/projects/fprime/config/PolyDbImplCfg.hpp | /*
* PolyDbImplCfg.hpp
*
* Created on: Mar 13, 2015
* Author: tcanham
*/
#ifndef POLYDB_POLYDBIMPLCFG_HPP_
#define POLYDB_POLYDBIMPLCFG_HPP_
namespace {
enum {
POLYDB_NUM_DB_ENTRIES = 25
};
}
#endif /* POLYDB_POLYDBIMPLCFG_HPP_ */
| hpp |
fprime | data/projects/fprime/config/CommandDispatcherImplCfg.hpp | /*
* CmdDispatcherImplCfg.hpp
*
* Created on: May 6, 2015
* Author: tcanham
*/
#ifndef CMDDISPATCHER_COMMANDDISPATCHERIMPLCFG_HPP_
#define CMDDISPATCHER_COMMANDDISPATCHERIMPLCFG_HPP_
// Define configuration values for dispatcher
enum {
CMD_DISPATCHER_DISPATCH_TABLE_SIZE = 100, // !< The size of the table holding opcodes to dispatch
CMD_DISPATCHER_SEQUENCER_TABLE_SIZE = 25, // !< The size of the table holding commands in progress
};
#endif /* CMDDISPATCHER_COMMANDDISPATCHERIMPLCFG_HPP_ */
| hpp |
fprime | data/projects/fprime/Utils/CRCChecker.cpp | // ======================================================================
// \title CRCChecker.cpp
// \author ortega
// \brief cpp file for a crc32 checker
//
// \copyright
// Copyright 2009-2020, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
// ======================================================================
#include <FpConfig.hpp>
#include <cstdio> // For snprintf
#include <Utils/CRCChecker.hpp>
#include <Fw/Types/Assert.hpp>
#include <Os/File.hpp>
#include <Os/FileSystem.hpp>
#include <Utils/Hash/Hash.hpp>
namespace Utils {
crc_stat_t create_checksum_file(const char* const fname)
{
FW_ASSERT(fname != nullptr);
FwSignedSizeType i;
FwSignedSizeType blocks;
FwSignedSizeType remaining_bytes;
FwSignedSizeType filesize;
Os::File f;
Os::FileSystem::Status fs_stat;
Os::File::Status stat;
Utils::Hash hash;
U32 checksum;
I32 s_stat;
FwSignedSizeType int_file_size;
FwSignedSizeType bytes_to_read;
FwSignedSizeType bytes_to_write;
CHAR hashFilename[CRC_MAX_FILENAME_SIZE];
U8 block_data[CRC_FILE_READ_BLOCK];
fs_stat = Os::FileSystem::getFileSize(fname, filesize);
if(fs_stat != Os::FileSystem::OP_OK)
{
return FAILED_FILE_SIZE;
}
int_file_size = filesize;
// Open file
stat = f.open(fname, Os::File::OPEN_READ);
if(stat != Os::File::OP_OK)
{
return FAILED_FILE_OPEN;
}
// Read file
bytes_to_read = CRC_FILE_READ_BLOCK;
blocks = int_file_size / CRC_FILE_READ_BLOCK;
for(i = 0; i < blocks; i++)
{
stat = f.read(block_data, bytes_to_read);
if(stat != Os::File::OP_OK || bytes_to_read != CRC_FILE_READ_BLOCK)
{
f.close();
return FAILED_FILE_READ;
}
hash.update(block_data, bytes_to_read);
}
remaining_bytes = int_file_size % CRC_FILE_READ_BLOCK;
bytes_to_read = remaining_bytes;
if(remaining_bytes > 0)
{
stat = f.read(block_data, bytes_to_read);
if(stat != Os::File::OP_OK || bytes_to_read != remaining_bytes)
{
f.close();
return FAILED_FILE_READ;
}
hash.update(block_data, remaining_bytes);
}
// close file
f.close();
// generate checksum
hash.final(checksum);
// open checksum file
s_stat = snprintf(hashFilename, CRC_MAX_FILENAME_SIZE, "%s%s", fname, HASH_EXTENSION_STRING);
FW_ASSERT(s_stat > 0);
stat = f.open(hashFilename, Os::File::OPEN_WRITE);
if(stat != Os::File::OP_OK)
{
return FAILED_FILE_CRC_OPEN;
}
// Write checksum file
bytes_to_write = sizeof(checksum);
stat = f.write(reinterpret_cast<U8*>(&checksum), bytes_to_write);
if(stat != Os::File::OP_OK || sizeof(checksum) != bytes_to_write)
{
f.close();
return FAILED_FILE_CRC_WRITE;
}
// close checksum file
f.close();
return PASSED_FILE_CRC_WRITE;
}
crc_stat_t read_crc32_from_file(const char* const fname, U32 &checksum_from_file) {
Os::File f;
Os::File::Status stat;
char hashFilename[CRC_MAX_FILENAME_SIZE];
FW_ASSERT(fname != nullptr);
// open checksum file
I32 s_stat = snprintf(hashFilename, CRC_MAX_FILENAME_SIZE, "%s%s", fname, HASH_EXTENSION_STRING);
FW_ASSERT(s_stat > 0);
stat = f.open(hashFilename, Os::File::OPEN_READ);
if(stat != Os::File::OP_OK)
{
return FAILED_FILE_CRC_OPEN;
}
// Read checksum file
FwSignedSizeType checksum_from_file_size = static_cast<FwSignedSizeType>(sizeof(checksum_from_file));
stat = f.read(reinterpret_cast<U8*>(&checksum_from_file), checksum_from_file_size);
if(stat != Os::File::OP_OK || checksum_from_file_size != sizeof(checksum_from_file))
{
f.close();
return FAILED_FILE_CRC_READ;
}
// close checksum file
f.close();
return PASSED_FILE_CRC_CHECK;
}
crc_stat_t verify_checksum(const char* const fname, U32 &expected, U32 &actual)
{
FW_ASSERT(fname != nullptr);
FwSignedSizeType i;
FwSignedSizeType blocks;
PlatformIntType remaining_bytes;
FwSignedSizeType filesize;
Os::File f;
Os::FileSystem::Status fs_stat;
Os::File::Status stat;
Utils::Hash hash;
U32 checksum;
U32 checksum_from_file;
FwSignedSizeType int_file_size;
FwSignedSizeType bytes_to_read;
U8 block_data[CRC_FILE_READ_BLOCK];
fs_stat = Os::FileSystem::getFileSize(fname, filesize);
if(fs_stat != Os::FileSystem::OP_OK)
{
return FAILED_FILE_SIZE;
}
int_file_size = static_cast<NATIVE_INT_TYPE>(filesize);
if(static_cast<FwSignedSizeType>(int_file_size) != filesize)
{
return FAILED_FILE_SIZE_CAST;
}
// Open file
stat = f.open(fname, Os::File::OPEN_READ);
if(stat != Os::File::OP_OK)
{
return FAILED_FILE_OPEN;
}
// Read file
bytes_to_read = CRC_FILE_READ_BLOCK;
blocks = filesize / CRC_FILE_READ_BLOCK;
for(i = 0; i < blocks; i++)
{
stat = f.read(block_data, bytes_to_read);
if(stat != Os::File::OP_OK || bytes_to_read != CRC_FILE_READ_BLOCK)
{
f.close();
return FAILED_FILE_READ;
}
hash.update(block_data, bytes_to_read);
}
remaining_bytes = int_file_size % CRC_FILE_READ_BLOCK;
bytes_to_read = remaining_bytes;
if(remaining_bytes > 0)
{
stat = f.read(block_data, bytes_to_read);
if(stat != Os::File::OP_OK || bytes_to_read != remaining_bytes)
{
f.close();
return FAILED_FILE_READ;
}
hash.update(block_data, remaining_bytes);
}
// close file
f.close();
// generate checksum
hash.final(checksum);
crc_stat_t crcstat = read_crc32_from_file(fname, checksum_from_file);
if (crcstat != PASSED_FILE_CRC_CHECK) {
return crcstat;
}
// compare checksums
if(checksum != checksum_from_file)
{
expected = checksum_from_file;
actual = checksum;
return FAILED_FILE_CRC_CHECK;
}
expected = checksum_from_file;
actual = checksum;
return PASSED_FILE_CRC_CHECK;
}
}
| cpp |
fprime | data/projects/fprime/Utils/RateLimiter.hpp | // ======================================================================
// \title RateLimiter.hpp
// \author vwong
// \brief hpp file for a rate limiter utility class
//
// \copyright
// Copyright (C) 2009-2020 California Institute of Technology.
//
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
// ======================================================================
#ifndef RateLimiter_HPP
#define RateLimiter_HPP
#include <FpConfig.hpp>
#include <Fw/Time/Time.hpp>
namespace Utils {
class RateLimiter
{
public:
// Construct with defined cycles
RateLimiter(U32 counterCycle, U32 timeCycle);
// Construct with cycles set to 0
RateLimiter();
public:
// Adjust cycles at run-time
void setCounterCycle(U32 counterCycle);
void setTimeCycle(U32 timeCycle);
// Main point of entry
//
// It will only factor in counter or time, whichever one has a cycle defined
//
// If both are defined, then satisfying _either_ one will work
// e.g. I want to trigger only once every X times or once every Y
// seconds, whichever comes first
//
// The argument-less version is a shorthand for counter-only RateLimiters
// If a time cycle is defined but the argument-less version is called,
// RateLimiter assumes the client forgot to supply a time, and asserts
//
bool trigger(Fw::Time time);
bool trigger();
// Manual state adjustments, if necessary
void reset();
void resetCounter();
void resetTime();
void setCounter(U32);
void setTime(Fw::Time time);
private:
// Helper functions to update each independently
bool shouldCounterTrigger();
bool shouldTimeTrigger(Fw::Time time);
void updateCounter(bool triggered);
void updateTime(bool triggered, Fw::Time time);
private:
// parameters
U32 m_counterCycle;
U32 m_timeCycle;
// state
U32 m_counter;
Fw::Time m_time;
bool m_timeAtNegativeInfinity;
};
} // end namespace Utils
#endif
| hpp |
fprime | data/projects/fprime/Utils/LockGuard.hpp | // ======================================================================
// \title LockGuard.hpp
// \author vwong
// \brief hpp file for a RAII-style lock guard utility class
//
// \copyright
// Copyright (C) 2009-2020 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
// ======================================================================
#ifndef LockGuard_HPP
#define LockGuard_HPP
#include <FpConfig.hpp>
#include <Os/Mutex.hpp>
namespace Utils {
class LockGuard
{
public:
// Construct and lock associated mutex
LockGuard(Os::Mutex& mutex);
// Destruct and unlock associated mutex
~LockGuard();
private:
// parameters
Os::Mutex& m_mutex;
};
} // end namespace Utils
#endif
| hpp |
fprime | data/projects/fprime/Utils/RateLimiter.cpp | // ======================================================================
// \title RateLimiter.cpp
// \author vwong
// \brief cpp file for a rate limiter utility class
//
// \copyright
// Copyright (C) 2009-2020 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
// ======================================================================
#include <Utils/RateLimiter.hpp>
namespace Utils {
RateLimiter ::
RateLimiter (
U32 counterCycle,
U32 timeCycle
) :
m_counterCycle(counterCycle),
m_timeCycle(timeCycle)
{
this->reset();
}
RateLimiter ::
RateLimiter () :
m_counterCycle(0),
m_timeCycle(0)
{
this->reset();
}
void RateLimiter ::
setCounterCycle(
U32 counterCycle
)
{
this->m_counterCycle = counterCycle;
}
void RateLimiter ::
setTimeCycle(
U32 timeCycle
)
{
this->m_timeCycle = timeCycle;
}
void RateLimiter ::
reset()
{
this->resetCounter();
this->resetTime();
}
void RateLimiter ::
resetCounter()
{
this->m_counter = 0;
}
void RateLimiter ::
resetTime()
{
this->m_time = Fw::Time();
this->m_timeAtNegativeInfinity = true;
}
void RateLimiter ::
setCounter(
U32 counter
)
{
this->m_counter = counter;
}
void RateLimiter ::
setTime(
Fw::Time time
)
{
this->m_time = time;
this->m_timeAtNegativeInfinity = false;
}
bool RateLimiter ::
trigger(
Fw::Time time
)
{
// NB: this implements a 4-bit decision, logically equivalent to this pseudo-code
//
// A = HAS_COUNTER, B = HAS_TIME, C = COUNTER_TRIGGER, D = TIME_TRIGGER
//
// if (!A && !B) => true
// if (A && B) => C || D
// if (A) => C
// if (B) => D
// false
//
if (this->m_counterCycle == 0 && this->m_timeCycle == 0) {
return true;
}
// evaluate trigger criteria
bool shouldTrigger = false;
if (this->m_counterCycle > 0) {
shouldTrigger = shouldTrigger || this->shouldCounterTrigger();
}
if (this->m_timeCycle > 0) {
shouldTrigger = shouldTrigger || this->shouldTimeTrigger(time);
}
// update states
if (this->m_counterCycle > 0) {
this->updateCounter(shouldTrigger);
}
if (this->m_timeCycle > 0) {
this->updateTime(shouldTrigger, time);
}
return shouldTrigger;
}
bool RateLimiter ::
trigger()
{
FW_ASSERT(this->m_timeCycle == 0);
return trigger(Fw::Time::zero());
}
bool RateLimiter ::
shouldCounterTrigger()
{
FW_ASSERT(this->m_counterCycle > 0);
// trigger at 0
bool shouldTrigger = (this->m_counter == 0);
return shouldTrigger;
}
bool RateLimiter ::
shouldTimeTrigger(Fw::Time time)
{
FW_ASSERT(this->m_timeCycle > 0);
// trigger at prev trigger time + time cycle seconds OR when time is at negative infinity
Fw::Time timeCycle = Fw::Time(this->m_timeCycle, 0);
Fw::Time nextTrigger = Fw::Time::add(this->m_time, timeCycle);
bool shouldTrigger = (time >= nextTrigger) || this->m_timeAtNegativeInfinity;
return shouldTrigger;
}
void RateLimiter ::
updateCounter(bool triggered)
{
FW_ASSERT(this->m_counterCycle > 0);
if (triggered) {
// triggered, set to next state
this->m_counter = 1;
} else {
// otherwise, just increment and maybe wrap
if (++this->m_counter >= this->m_counterCycle) {
this->m_counter = 0;
}
}
}
void RateLimiter ::
updateTime(bool triggered, Fw::Time time)
{
FW_ASSERT(this->m_timeCycle > 0);
if (triggered) {
// mark time of trigger
this->m_time = time;
}
this->m_timeAtNegativeInfinity = false;
}
} // end namespace Utils
| cpp |
fprime | data/projects/fprime/Utils/LockGuard.cpp | // ======================================================================
// \title LockGuard.cpp
// \author vwong
// \brief cpp file for a lock guard utility class
//
//
// \copyright
// Copyright (C) 2009-2020 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
// ======================================================================
#include "Utils/LockGuard.hpp"
namespace Utils {
LockGuard ::
LockGuard (
Os::Mutex& mutex
) :
m_mutex(mutex)
{
this->m_mutex.lock();
}
LockGuard ::
~LockGuard ()
{
this->m_mutex.unLock();
}
} // end namespace Utils
| cpp |
fprime | data/projects/fprime/Utils/TokenBucket.hpp | // ======================================================================
// \title TokenBucket.hpp
// \author vwong
// \brief hpp file for a rate limiter utility class
//
// \copyright
//
// Copyright (C) 2009-2020 California Institute of Technology.
//
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
// ======================================================================
#ifndef TokenBucket_HPP
#define TokenBucket_HPP
#include <FpConfig.hpp>
#include <Fw/Time/Time.hpp>
#define MAX_TOKEN_BUCKET_TOKENS 1000
namespace Utils {
class TokenBucket
{
public:
// Full constructor
//
// replenishInterval is in microseconds
//
TokenBucket(U32 replenishInterval, U32 maxTokens, U32 replenishRate, U32 startTokens, Fw::Time startTime);
// replenishRate=1, startTokens=maxTokens, startTime=0
TokenBucket(U32 replenishInterval, U32 maxTokens);
public:
// Adjust settings at runtime
void setMaxTokens(U32 maxTokens);
void setReplenishInterval(U32 replenishInterval);
void setReplenishRate(U32 replenishRate);
U32 getMaxTokens() const;
U32 getReplenishInterval() const;
U32 getReplenishRate() const;
U32 getTokens() const;
// Manual replenish
void replenish();
// Main point of entry
//
// Evaluates time since last trigger to determine number of tokens to
// replenish. If time moved backwards, always returns false.
//
// If number of tokens is not zero, consumes one and returns true.
// Otherwise, returns false.
//
bool trigger(const Fw::Time time);
private:
// parameters
U32 m_replenishInterval;
U32 m_maxTokens;
U32 m_replenishRate;
// state
U32 m_tokens;
Fw::Time m_time;
};
} // end namespace Utils
#endif
| hpp |
fprime | data/projects/fprime/Utils/CRCChecker.hpp | // ======================================================================
// \title CRCChecker.hpp
// \author ortega
// \brief hpp file for a crc32 checker
//
// \copyright
// Copyright 2009-2020, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
// ======================================================================
#ifndef CRC_CHECKER_HPP
#define CRC_CHECKER_HPP
#include <FpConfig.hpp>
namespace Utils {
static const NATIVE_INT_TYPE CRC_FILE_READ_BLOCK = 2048;
static const U32 CRC_MAX_FILENAME_SIZE = 128; // TODO use a config variable
typedef enum
{
PASSED_FILE_CRC_CHECK = 0,
PASSED_FILE_CRC_WRITE,
FAILED_FILE_SIZE,
FAILED_FILE_SIZE_CAST,
FAILED_FILE_OPEN,
FAILED_FILE_READ,
FAILED_FILE_CRC_OPEN,
FAILED_FILE_CRC_READ,
FAILED_FILE_CRC_WRITE,
FAILED_FILE_CRC_CHECK
} crc_stat_t;
crc_stat_t create_checksum_file(const char* const filename);
crc_stat_t read_crc32_from_file(const char* const fname, U32 &checksum_from_file);
crc_stat_t verify_checksum(const char* const filename, U32 &expected, U32 &actual);
}
#endif
| hpp |
fprime | data/projects/fprime/Utils/TokenBucket.cpp | // ======================================================================
// \title TokenBucket.cpp
// \author vwong
// \brief cpp file for a rate limiter utility class
//
// \copyright
//
// Copyright (C) 2009-2020 California Institute of Technology.
//
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
// ======================================================================
#include <Utils/TokenBucket.hpp>
namespace Utils {
TokenBucket ::
TokenBucket (
U32 replenishInterval,
U32 maxTokens,
U32 replenishRate,
U32 startTokens,
Fw::Time startTime
) :
m_replenishInterval(replenishInterval),
m_maxTokens(maxTokens),
m_replenishRate(replenishRate),
m_tokens(startTokens),
m_time(startTime)
{
}
TokenBucket ::
TokenBucket (
U32 replenishInterval,
U32 maxTokens
) :
m_replenishInterval(replenishInterval),
m_maxTokens(maxTokens),
m_replenishRate(1),
m_tokens(maxTokens),
m_time(0, 0)
{
FW_ASSERT(this->m_maxTokens <= MAX_TOKEN_BUCKET_TOKENS, this->m_maxTokens);
}
void TokenBucket ::
setReplenishInterval(
U32 replenishInterval
)
{
this->m_replenishInterval = replenishInterval;
}
void TokenBucket ::
setMaxTokens(
U32 maxTokens
)
{
this->m_maxTokens = maxTokens;
}
void TokenBucket ::
setReplenishRate(
U32 replenishRate
)
{
this->m_replenishRate = replenishRate;
}
void TokenBucket ::
replenish()
{
if (this->m_tokens < this->m_maxTokens) {
this->m_tokens = this->m_maxTokens;
}
}
U32 TokenBucket ::
getReplenishInterval() const
{
return this->m_replenishInterval;
}
U32 TokenBucket ::
getMaxTokens() const
{
return this->m_maxTokens;
}
U32 TokenBucket ::
getReplenishRate() const
{
return this->m_replenishRate;
}
U32 TokenBucket ::
getTokens() const
{
return this->m_tokens;
}
bool TokenBucket ::
trigger(
const Fw::Time time
)
{
// attempt replenishing
if (this->m_replenishRate > 0) {
Fw::Time replenishInterval = Fw::Time(this->m_replenishInterval / 1000000, this->m_replenishInterval % 1000000);
Fw::Time nextTime = Fw::Time::add(this->m_time, replenishInterval);
while (this->m_tokens < this->m_maxTokens && nextTime <= time) {
// replenish by replenish rate, or up to maxTokens
this->m_tokens += FW_MIN(this->m_replenishRate, this->m_maxTokens - this->m_tokens);
this->m_time = nextTime;
nextTime = Fw::Time::add(this->m_time, replenishInterval);
}
if (this->m_tokens >= this->m_maxTokens && this->m_time < time) {
this->m_time = time;
}
}
// attempt consuming token
if (this->m_tokens > 0) {
this->m_tokens--;
return true;
} else {
return false;
}
}
} // end namespace Utils
| cpp |
fprime | data/projects/fprime/Utils/TestUtils.hpp | // ======================================================================
// \title TestUtils.hpp
// \author vwong
// \brief hpp file for unit test utility macros
//
// \copyright
//
// Copyright (C) 2009-2020 California Institute of Technology.
//
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
// ======================================================================
#ifndef TESTUTILS_HPP
#define TESTUTILS_HPP
// HOW TO USE:
//
// 1) in Tester.cpp, include this file
// e.g.: #include <Utils/TestUtils.hpp>
//
// 2) in Tester.cpp, set your component name in TEST_COMP macro
// e.g.: #define TEST_COMP PwrSwitchManagerComponentImpl
//
// 3) make sure INSTANCE and CMD_SEQ are also defined in Tester.cpp (they
// should be autogenerated)
//
// List of macros:
//
// - SEND_CMD(cmd, status, ...)
// - SEND_CMD_NO_EXPECT(cmd, ...)
// - ASSERT_LAST_CMD(cmd, status)
// - ASSERT_LAST_TLM(name, value)
// - ASSERT_LAST_EVENT(name, ...)
// - ASSERT_LAST_PORT_OUT(port, ...)
//
// See below for detailed descriptions
// SEND_CMD
//
// Send a command and expect a response status. This command essentially calls
// sendCmd, doDispatch, and asserts a command response. The last command
// response received must be for the command sent here for it to validate, i.e.
// it may not work well if your component interleaves command responses.
//
// Example:
//
// SEND_CMD(PWR_SW_MGR_PWR_ON, Fw::CmdResponse::OK, channel);
// SEND_CMD(PWR_SW_MGR_SET_DUTY_CYCLE, Fw::CmdResponse::OK, channel, dutyCycle);
// SEND_CMD(PWR_SW_MGR_PWR_ON, Fw::COMMAND_EXECUTION_ERROR, illegalChannel);
//
#define SEND_CMD(cmd, status, ...) \
SEND_CMD_COMP(TEST_COMP, cmd, status, ## __VA_ARGS__)
#define SEND_CMD_COMP(comp, cmd, status, ...) \
this->sendCmd_ ## cmd(INSTANCE, CMD_SEQ, ## __VA_ARGS__); \
this->component.doDispatch(); \
ASSERT_LAST_CMD(cmd, status);
// SEND_CMD_NO_EXPECT
//
// Send a command and performs dispatch, without asserting any command response.
//
// Example:
//
// SEND_CMD_NO_EXPECT(FILE_DWN_SEND_APID, 100, 0, 0, 0);
// // ...
//
#define SEND_CMD_NO_EXPECT(cmd, ...) \
SEND_CMD_COMP_NO_EXPECT(TEST_COMP, cmd, ## __VA_ARGS__)
#define SEND_CMD_COMP_NO_EXPECT(comp, cmd, ...) \
this->sendCmd_ ## cmd(INSTANCE, CMD_SEQ, ## __VA_ARGS__); \
this->component.doDispatch();
// ASSERT_LAST_CMD
//
// Assert response status of command. This macro checks both that there was a
// response and that the response is as expected and is for the command
// specified.
//
// Example:
//
// SEND_CMD_NO_EXPECT(FILE_DWN_SEND_APID, 100, 0, 0, 0);
// // ...
// ASSERT_LAST_CMD(FILE_DWN_SEND_APID, Fw::CmdResponse::OK);
//
#define ASSERT_LAST_CMD(cmd, status) \
ASSERT_LAST_CMD_COMP(TEST_COMP, cmd, status)
#define ASSERT_LAST_CMD_COMP(comp, cmd, status) \
ASSERT_GT(this->cmdResponseHistory->size(), 0); \
ASSERT_CMD_RESPONSE(this->cmdResponseHistory->size()-1, comp::OPCODE_ ## cmd, CMD_SEQ, status);
// ASSERT_LAST_TLM
//
// Assert the value last received in a given channel.
//
// Example:
//
// ASSERT_LAST_TLM(NeaCamManager_ImageDataSize, dataSize);
// ASSERT_LAST_TLM(NeaCamManager_PatternDataSize, 0);
//
#define ASSERT_LAST_TLM(name, value) \
ASSERT_GT(this->tlmHistory_ ## name->size(), 0); \
ASSERT_TLM_ ## name(this->tlmHistory_ ## name->size()-1, value);
// ASSERT_LAST_EVENT
//
// Assert the arguments in the last received EVR of a given name.
//
// Example:
//
// SEND_CMD(PWR_SW_MGR_SET_DUTY_CYCLE, Fw::COMMAND_VALIDATION_ERROR, 0, 0);
// ASSERT_LAST_EVENT(PwrSwitchManager_DutyCyclingNotEnabled, i);
//
#define ASSERT_LAST_EVENT(name, ...) \
ASSERT_GT(this->eventHistory_ ## name->size(), 0); \
ASSERT_EVENTS_ ## name(this->eventHistory_ ## name->size()-1, ## __VA_ARGS__);
// ASSERT_LAST_PORT_OUT
//
// Assert the arguments in the last output port call of a given port.
//
// Example:
//
// this->invoke_to_PingRecv(0, 0xDEADBEEF);
// this->component.doDispatch();
// ASSERT_LAST_PORT_OUT(PingResponse, 0, 0xDEADBEEF);
//
#define ASSERT_LAST_PORT_OUT(port, ...) \
ASSERT_GT(this->fromPortHistory_ ## port->size(), 0); \
ASSERT_from_ ## port(__VA_ARGS__);
#endif
| hpp |
fprime | data/projects/fprime/Utils/Hash/HashBuffer.hpp | // ======================================================================
// \title Hash.hpp
// \author dinkel
// \brief hpp file for Hash class
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#ifndef UTILS_HASH_BUFFER_HPP
#define UTILS_HASH_BUFFER_HPP
#include <FpConfig.hpp>
#include <Fw/Types/Serializable.hpp>
#include <Fw/Types/Assert.hpp>
#include <Utils/Hash/HashConfig.hpp>
namespace Utils {
//! \class HashBuffer
//! \brief A container class for holding a hash buffer
//!
class HashBuffer : public Fw::SerializeBufferBase {
public:
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
//! Construct a HashBuffer object
//!
HashBuffer(const U8 *args, NATIVE_UINT_TYPE size);
HashBuffer(const HashBuffer& other);
HashBuffer();
//! Destroy a HashBuffer object
//!
virtual ~HashBuffer();
// ----------------------------------------------------------------------
// Public instance methods
// ----------------------------------------------------------------------
//! Assign a hash buffer from another hash buffer
//!
HashBuffer& operator=(const HashBuffer& other);
//! Compare two hash buffers for equality
//!
bool operator==(const HashBuffer& other) const;
//! Compare two hash buffers for inequality
//!
bool operator!=(const HashBuffer& other) const;
//! Get the total buffer length of a hash buffer
//!
NATIVE_UINT_TYPE getBuffCapacity() const; // !< returns capacity, not current size, of buffer
//! Get a pointer to the buffer within the hash buffer
//!
U8* getBuffAddr();
const U8* getBuffAddr() const;
private:
// ----------------------------------------------------------------------
// Private member variables
// ----------------------------------------------------------------------
//! The buffer which stores the hash digest
//!
U8 m_bufferData[HASH_DIGEST_LENGTH]; // packet data buffer
};
}
#endif
| hpp |
fprime | data/projects/fprime/Utils/Hash/HashConfig.hpp | #ifndef UTILS_HASH_CONFIG_HPP
#define UTILS_HASH_CONFIG_HPP
//! Choose the hash implementation that you want to use
//! by including the implementation hash header that
//! you are interested in. Ie. This could look like:
//!
//! #include <Utils/Hash/openssl/SHA256.hpp>
//!
#include <Utils/Hash/libcrc/CRC32.hpp>
#endif
| hpp |
fprime | data/projects/fprime/Utils/Hash/HashCommon.cpp | #include <Utils/Hash/Hash.hpp>
namespace Utils {
const char* Hash ::
getFileExtensionString()
{
return HASH_EXTENSION_STRING;
}
void Hash ::
addFileExtension(
const Fw::StringBase& baseName,
Fw::StringBase& extendedName
) {
extendedName.format("%s%s", baseName.toChar(), HASH_EXTENSION_STRING);
}
NATIVE_UINT_TYPE Hash ::
getFileExtensionLength()
{
// Size of returns the size including the '\0' character.
// We want to return just the size of the string.
return sizeof(HASH_EXTENSION_STRING) - 1;
}
}
| cpp |
fprime | data/projects/fprime/Utils/Hash/HashBufferCommon.cpp | #include <Utils/Hash/HashBuffer.hpp>
#include <cstring>
namespace Utils {
HashBuffer::HashBuffer() {
}
HashBuffer::HashBuffer(const U8 *args, NATIVE_UINT_TYPE size) {
Fw::SerializeStatus stat = Fw::SerializeBufferBase::setBuff(args,size);
FW_ASSERT(Fw::FW_SERIALIZE_OK == stat,static_cast<NATIVE_INT_TYPE>(stat));
}
HashBuffer::~HashBuffer() {
}
HashBuffer::HashBuffer(const HashBuffer& other) : Fw::SerializeBufferBase() {
Fw::SerializeStatus stat = Fw::SerializeBufferBase::setBuff(other.m_bufferData,other.getBuffLength());
FW_ASSERT(Fw::FW_SERIALIZE_OK == stat,static_cast<NATIVE_INT_TYPE>(stat));
}
HashBuffer& HashBuffer::operator=(const HashBuffer& other) {
if(this == &other) {
return *this;
}
Fw::SerializeStatus stat = Fw::SerializeBufferBase::setBuff(other.m_bufferData,other.getBuffLength());
FW_ASSERT(Fw::FW_SERIALIZE_OK == stat,static_cast<NATIVE_INT_TYPE>(stat));
return *this;
}
bool HashBuffer::operator==(const HashBuffer& other) const {
if( (this->getBuffLength() == other.getBuffLength()) &&
(memcmp(this->getBuffAddr(), other.getBuffAddr(), this->getBuffLength()) != 0) ){
return false;
}
return true;
}
bool HashBuffer::operator!=(const HashBuffer& other) const {
return !(*this == other);
}
const U8* HashBuffer::getBuffAddr() const {
return this->m_bufferData;
}
U8* HashBuffer::getBuffAddr() {
return this->m_bufferData;
}
NATIVE_UINT_TYPE HashBuffer::getBuffCapacity() const {
return sizeof(this->m_bufferData);
}
}
| cpp |
fprime | data/projects/fprime/Utils/Hash/Hash.hpp | // ======================================================================
// \title Hash.hpp
// \author dinkel
// \brief hpp file for Hash class
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#ifndef UTILS_HASH_HPP
#define UTILS_HASH_HPP
#include "Fw/Types/StringType.hpp"
#include <Utils/Hash/HashBuffer.hpp>
namespace Utils {
//! \class Hash
//! \brief A generic interface for creating and comparing hash values
//!
class Hash {
public:
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
//! Construct a Hash object
//!
Hash();
//! Destroy a Hash object
//!
~Hash();
public:
// ----------------------------------------------------------------------
// Public static methods
// ----------------------------------------------------------------------
//! Create a hash value all at once from raw data
//! \param data: pointer to start of data
//! \param len: length of the data
//! \param buffer: filled with resulting hash value
static void hash(
const void *data,
const NATIVE_INT_TYPE len,
HashBuffer& buffer
);
public:
// ----------------------------------------------------------------------
// Public instance methods
// ----------------------------------------------------------------------
//! Initialize a Hash object for incremental hash computation
//!
void init();
//! Set hash value to specified value
//!
void setHashValue(
HashBuffer &value //! Hash value
);
//! Update an incremental computation with new data
//! \param data: pointer to start of data to add to hash calculation
//! \param len: length of data to add to hash calculation
void update(
const void *const data,
const NATIVE_INT_TYPE len
);
//! Finalize an incremental computation and return the result
//!
void final(
HashBuffer& buffer //! The result
);
//! Finalize an incremental computation and return the result
//!
void final(U32 &hashvalue);
//! Get the file extension for the supported hash type
//! E.g., could return "SHA256"
//!
static const char* getFileExtensionString();
//! Add the extension for the supported hash type
//!
static void addFileExtension(
const Fw::StringBase& baseName, //!< The base name
Fw::StringBase& extendedName //!< The extended name
);
//! Get the length of the file extension string
//!
static NATIVE_UINT_TYPE getFileExtensionLength();
private:
// ----------------------------------------------------------------------
// Private member variables
// ----------------------------------------------------------------------
//! The hash handle
//!
HASH_HANDLE_TYPE hash_handle;
};
}
#endif
| hpp |
fprime | data/projects/fprime/Utils/Hash/openssl/sha.h | /* crypto/sha/sha.h */
/* Copyright (C) 1995-1998 Eric Young ([email protected])
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young ([email protected]).
* The implementation was written so as to conform with Netscape's SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson ([email protected]).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young ([email protected])"
* The word 'cryptographic' can be left out if the routines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson ([email protected])"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publicly available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#ifndef HEADER_SHA_H
# define HEADER_SHA_H
# include <openssl/e_os2.h>
# include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
# if defined(OPENSSL_NO_SHA) || (defined(OPENSSL_NO_SHA0) && defined(OPENSSL_NO_SHA1))
# error SHA is disabled.
# endif
# if defined(OPENSSL_FIPS)
# define FIPS_SHA_SIZE_T size_t
# endif
/*-
* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
* ! SHA_LONG has to be at least 32 bits wide. If it's wider, then !
* ! SHA_LONG_LOG2 has to be defined along. !
* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
*/
# if defined(__LP32__)
# define SHA_LONG unsigned long
# elif defined(OPENSSL_SYS_CRAY) || defined(__ILP64__)
# define SHA_LONG unsigned long
# define SHA_LONG_LOG2 3
# else
# define SHA_LONG unsigned int
# endif
# define SHA_LBLOCK 16
# define SHA_CBLOCK (SHA_LBLOCK*4)/* SHA treats input data as a
* contiguous array of 32 bit wide
* big-endian values. */
# define SHA_LAST_BLOCK (SHA_CBLOCK-8)
# define SHA_DIGEST_LENGTH 20
typedef struct SHAstate_st {
SHA_LONG h0, h1, h2, h3, h4;
SHA_LONG Nl, Nh;
SHA_LONG data[SHA_LBLOCK];
unsigned int num;
} SHA_CTX;
# ifndef OPENSSL_NO_SHA0
# ifdef OPENSSL_FIPS
int private_SHA_Init(SHA_CTX *c);
# endif
int SHA_Init(SHA_CTX *c);
int SHA_Update(SHA_CTX *c, const void *data, size_t len);
int SHA_Final(unsigned char *md, SHA_CTX *c);
unsigned char *SHA(const unsigned char *d, size_t n, unsigned char *md);
void SHA_Transform(SHA_CTX *c, const unsigned char *data);
# endif
# ifndef OPENSSL_NO_SHA1
# ifdef OPENSSL_FIPS
int private_SHA1_Init(SHA_CTX *c);
# endif
int SHA1_Init(SHA_CTX *c);
int SHA1_Update(SHA_CTX *c, const void *data, size_t len);
int SHA1_Final(unsigned char *md, SHA_CTX *c);
unsigned char *SHA1(const unsigned char *d, size_t n, unsigned char *md);
void SHA1_Transform(SHA_CTX *c, const unsigned char *data);
# endif
# define SHA256_CBLOCK (SHA_LBLOCK*4)/* SHA-256 treats input data as a
* contiguous array of 32 bit wide
* big-endian values. */
# define SHA224_DIGEST_LENGTH 28
# define SHA256_DIGEST_LENGTH 32
typedef struct SHA256state_st {
SHA_LONG h[8];
SHA_LONG Nl, Nh;
SHA_LONG data[SHA_LBLOCK];
unsigned int num, md_len;
} SHA256_CTX;
# ifndef OPENSSL_NO_SHA256
# ifdef OPENSSL_FIPS
int private_SHA224_Init(SHA256_CTX *c);
int private_SHA256_Init(SHA256_CTX *c);
# endif
int SHA224_Init(SHA256_CTX *c);
int SHA224_Update(SHA256_CTX *c, const void *data, size_t len);
int SHA224_Final(unsigned char *md, SHA256_CTX *c);
unsigned char *SHA224(const unsigned char *d, size_t n, unsigned char *md);
int SHA256_Init(SHA256_CTX *c);
int SHA256_Update(SHA256_CTX *c, const void *data, size_t len);
int SHA256_Final(unsigned char *md, SHA256_CTX *c);
unsigned char *SHA256(const unsigned char *d, size_t n, unsigned char *md);
void SHA256_Transform(SHA256_CTX *c, const unsigned char *data);
# endif
# define SHA384_DIGEST_LENGTH 48
# define SHA512_DIGEST_LENGTH 64
# ifndef OPENSSL_NO_SHA512
/*
* Unlike 32-bit digest algorithms, SHA-512 *relies* on SHA_LONG64
* being exactly 64-bit wide. See Implementation Notes in sha512.c
* for further details.
*/
/*
* SHA-512 treats input data as a
* contiguous array of 64 bit
* wide big-endian values.
*/
# define SHA512_CBLOCK (SHA_LBLOCK*8)
# if (defined(_WIN32) || defined(_WIN64)) && !defined(__MINGW32__)
# define SHA_LONG64 unsigned __int64
# define U64(C) C##UI64
# elif defined(__arch64__)
# define SHA_LONG64 unsigned long
# define U64(C) C##UL
# else
# define SHA_LONG64 unsigned long long
# define U64(C) C##ULL
# endif
typedef struct SHA512state_st {
SHA_LONG64 h[8];
SHA_LONG64 Nl, Nh;
union {
SHA_LONG64 d[SHA_LBLOCK];
unsigned char p[SHA512_CBLOCK];
} u;
unsigned int num, md_len;
} SHA512_CTX;
# endif
# ifndef OPENSSL_NO_SHA512
# ifdef OPENSSL_FIPS
int private_SHA384_Init(SHA512_CTX *c);
int private_SHA512_Init(SHA512_CTX *c);
# endif
int SHA384_Init(SHA512_CTX *c);
int SHA384_Update(SHA512_CTX *c, const void *data, size_t len);
int SHA384_Final(unsigned char *md, SHA512_CTX *c);
unsigned char *SHA384(const unsigned char *d, size_t n, unsigned char *md);
int SHA512_Init(SHA512_CTX *c);
int SHA512_Update(SHA512_CTX *c, const void *data, size_t len);
int SHA512_Final(unsigned char *md, SHA512_CTX *c);
unsigned char *SHA512(const unsigned char *d, size_t n, unsigned char *md);
void SHA512_Transform(SHA512_CTX *c, const unsigned char *data);
# endif
#ifdef __cplusplus
}
#endif
#endif
| h |
fprime | data/projects/fprime/Utils/Hash/openssl/SHA256.cpp | // ======================================================================
// \title SHA256.cpp
// \author dinkel
// \brief cpp file for SHA implementation of Hash class
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include <Utils/Hash/Hash.hpp>
namespace Utils {
Hash ::
Hash()
{
this->init();
}
Hash ::
~Hash()
{
}
void Hash ::
hash(const void *const data, const NATIVE_INT_TYPE len, HashBuffer& buffer)
{
U8 out[SHA256_DIGEST_LENGTH];
U8* ret = SHA256(static_cast<const U8*>(data), len, out);
FW_ASSERT(ret != nullptr);
HashBuffer bufferOut(out, sizeof(out));
buffer = bufferOut;
}
void Hash ::
init()
{
int ret = SHA256_Init(&this->hash_handle);
FW_ASSERT(ret == 1);
}
void Hash ::
update(const void *const data, NATIVE_INT_TYPE len)
{
int ret = SHA256_Update(&this->hash_handle, static_cast<const U8*>(data), len);
FW_ASSERT(ret == 1);
}
void Hash ::
final(HashBuffer& buffer)
{
U8 out[SHA256_DIGEST_LENGTH];
int ret = SHA256_Final(out, &this->hash_handle);
FW_ASSERT(ret == 1);
HashBuffer bufferOut(out, sizeof(out));
buffer = bufferOut;
}
}
| cpp |
fprime | data/projects/fprime/Utils/Hash/openssl/SHA256.hpp | #ifndef UTILS_SHA256_CONFIG_HPP
#define UTILS_SHA256_CONFIG_HPP
// Include the sha library:
#include <Utils/Hash/openssl/sha.h>
//! Define the hash handle type for this
//! implementation. This is required.
#ifndef HASH_HANDLE_TYPE
#define HASH_HANDLE_TYPE SHA256_CTX
#endif
//! Define the size of a hash digest in bytes for this
//! implementation. This is required.
#ifndef HASH_DIGEST_LENGTH
#define HASH_DIGEST_LENGTH (SHA256_DIGEST_LENGTH)
#endif
//! Define the string to be used as a filename
//! extension (ie. file.txt.SHA256) for this
//! implementation. This is required.
#ifndef HASH_EXTENSION_STRING
#define HASH_EXTENSION_STRING (".SHA256")
#endif
#endif
| hpp |
fprime | data/projects/fprime/Utils/Hash/libcrc/CRC32.hpp | #ifndef UTILS_CRC32_CONFIG_HPP
#define UTILS_CRC32_CONFIG_HPP
// Include the lic crc c library:
extern "C" {
#include <Utils/Hash/libcrc/lib_crc.h>
}
//! Define the hash handle type for this
//! implementation. This is required.
#ifndef HASH_HANDLE_TYPE
#define HASH_HANDLE_TYPE U32
#endif
//! Define the size of a hash digest in bytes for this
//! implementation. This is required.
#ifndef HASH_DIGEST_LENGTH
#define HASH_DIGEST_LENGTH (4)
#endif
//! Define the string to be used as a filename
//! extension (ie. file.txt.SHA256) for this
//! implementation. This is required.
#ifndef HASH_EXTENSION_STRING
#define HASH_EXTENSION_STRING (".CRC32")
#endif
#endif
| hpp |
fprime | data/projects/fprime/Utils/Hash/libcrc/CRC32.cpp | // ======================================================================
// \title CRC32.cpp
// \author dinkel
// \brief cpp file for CRC32 implementation of Hash class
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include <Utils/Hash/Hash.hpp>
namespace Utils {
Hash ::
Hash()
{
this->init();
}
Hash ::
~Hash()
{
}
void Hash ::
hash(const void *const data, const NATIVE_INT_TYPE len, HashBuffer& buffer)
{
HASH_HANDLE_TYPE local_hash_handle;
local_hash_handle = 0xffffffffL;
FW_ASSERT(data);
char c;
for(int index = 0; index < len; index++) {
c = static_cast<const char*>(data)[index];
local_hash_handle = update_crc_32(local_hash_handle, c);
}
HashBuffer bufferOut;
// For CRC32 we need to return the one's complement of the result:
Fw::SerializeStatus status = bufferOut.serialize(~(local_hash_handle));
FW_ASSERT( Fw::FW_SERIALIZE_OK == status );
buffer = bufferOut;
}
void Hash ::
init()
{
this->hash_handle = 0xffffffffL;
}
void Hash ::
update(const void *const data, NATIVE_INT_TYPE len)
{
FW_ASSERT(data);
char c;
for(int index = 0; index < len; index++) {
c = static_cast<const char*>(data)[index];
this->hash_handle = update_crc_32(this->hash_handle, c);
}
}
void Hash ::
final(HashBuffer& buffer)
{
HashBuffer bufferOut;
// For CRC32 we need to return the one's complement of the result:
Fw::SerializeStatus status = bufferOut.serialize(~(this->hash_handle));
FW_ASSERT( Fw::FW_SERIALIZE_OK == status );
buffer = bufferOut;
}
void Hash ::
final(U32 &hashvalue)
{
FW_ASSERT(sizeof(this->hash_handle) == sizeof(U32));
// For CRC32 we need to return the one's complement of the result:
hashvalue = ~(this->hash_handle);
}
void Hash ::
setHashValue(HashBuffer &value)
{
Fw::SerializeStatus status = value.deserialize(this->hash_handle);
FW_ASSERT( Fw::FW_SERIALIZE_OK == status );
// Expecting `value` to already be one's complement; so doing one's complement
// here for correct hash updates
this->hash_handle = ~this->hash_handle;
}
}
| cpp |
fprime | data/projects/fprime/Utils/Hash/libcrc/lib_crc.h | /*******************************************************************\
* *
* Library : lib_crc *
* File : lib_crc.h *
* Author : Lammert Bies 1999-2008 *
* E-mail : [email protected] *
* Language : ANSI C *
* *
* *
* Description *
* =========== *
* *
* The file lib_crc.h contains public definitions and proto- *
* types for the CRC functions present in lib_crc.c. *
* *
* *
* Dependencies *
* ============ *
* *
* none *
* *
* *
* Modification history *
* ==================== *
* *
* Date Version Comment *
* *
* 2008-04-20 1.16 Added CRC-CCITT routine for Kermit *
* *
* 2007-04-01 1.15 Added CRC16 calculation for Modbus *
* *
* 2007-03-28 1.14 Added CRC16 routine for Sick devices *
* *
* 2005-12-17 1.13 Added CRC-CCITT with initial 0x1D0F *
* *
* 2005-02-14 1.12 Added CRC-CCITT with initial 0x0000 *
* *
* 2005-02-05 1.11 Fixed bug in CRC-DNP routine *
* *
* 2005-02-04 1.10 Added CRC-DNP routines *
* *
* 2005-01-07 1.02 Changes in tst_crc.c *
* *
* 1999-02-21 1.01 Added FALSE and TRUE mnemonics *
* *
* 1999-01-22 1.00 Initial source *
* *
\*******************************************************************/
#ifndef UTILS_HASH_LIB_CRC_HPP
#define UTILS_HASH_LIB_CRC_HPP
#define CRC_VERSION "1.16"
#define CRC_FALSE 0
#define CRC_TRUE 1
unsigned short update_crc_16( unsigned short crc, char c );
unsigned long update_crc_32( unsigned long crc, char c );
unsigned short update_crc_ccitt( unsigned short crc, char c );
unsigned short update_crc_dnp( unsigned short crc, char c );
unsigned short update_crc_kermit( unsigned short crc, char c );
unsigned short update_crc_sick( unsigned short crc, char c, char prev_byte );
#endif // UTILS_HASH_LIB_CRC_HPP
| h |
fprime | data/projects/fprime/Utils/Hash/libcrc/tst_crc.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "lib_crc.h"
/*******************************************************************\
* *
* Library : lib_crc *
* File : tst_crc.c *
* Author : Lammert Bies 1999-2008 *
* E-mail : [email protected] *
* Language : ANSI C *
* *
* *
* Description *
* =========== *
* *
* The file tst_crc.c contains a small sample program which *
* demonstrates the use of the functions for calculating the *
* CRC-CCITT, CRC-16 and CRC-32 values of data. The file cal- *
* culates the three different CRC's for a file whose name is *
* either provided at the command line, or typed in right *
* after the program has started. *
* *
* *
* Dependencies *
* ============ *
* *
* lib_crc.h CRC definitions and prototypes *
* lib_crc.c CRC routines *
* *
* *
* Modification history *
* ==================== *
* *
* Date Version Comment *
* *
* 2008-04-20 1.16 Added CRC-CCITT calculation for Kermit. *
* *
* 2007-05-01 1.15 Added CRC16 calculation for Modbus. *
* *
* 2007-03-28 1.14 Added CRC16 routine for Sick devices, *
* electronic devices used for measurement *
* and detection in industrial situations. *
* *
* 2005-12-17 1.13 Added CRC-CCITT with initial 0x1D0F *
* *
* 2005-02-14 1.12 Added CRC-CCITT with initial 0x0000 *
* *
* 2005-02-05 1.11 Fixed post processing bug in CRC-DNP. *
* *
* 2005-02-04 1.10 Added the CRC calculation for DNP 3.0, *
* a protocol used in the communication *
* between remote units and masters in the *
* electric utility industry. The method *
* of calculation is the same as CRC-16, *
* but with a different polynomial. *
* *
* 2005-01-07 1.02 Changed way program is used. When a *
* commandline parameter is present, the *
* program assumes it is a file, but when *
* invoked without a parameter the entered *
* string is used to calculate the CRC. *
* *
* CRC's are now printed in hexadecimal *
* decimal format. *
* *
* Let CRC-CCITT calculation start with *
* 0xffff as this is used in most imple- *
* mentations. *
* *
* 1999-02-21 1.01 none *
* *
* 1999-01-22 1.00 Initial source *
* *
\*******************************************************************/
#define MAX_STRING_SIZE 2048
void main( int argc, char *argv[] ) {
char input_string[MAX_STRING_SIZE];
char *ptr, *dest, hex_val, prev_byte;
unsigned short crc_16, crc_16_modbus, crc_ccitt_ffff, crc_ccitt_0000, crc_ccitt_1d0f, crc_dnp, crc_sick, crc_kermit;
unsigned short low_byte, high_byte;
unsigned long crc_32;
int a, ch, do_ascii, do_hex;
FILE *fp;
do_ascii = CRC_FALSE;
do_hex = CRC_FALSE;
printf( "\nCRC algorithm sample program\nLammert Bies, Version " CRC_VERSION "\n\n" );
if ( argc < 2 ) {
printf( "Usage: tst_crc [-a|-x] file1 ...\n\n" );
printf( " -a Program asks for ASCII input. Following parameters ignored.\n" );
printf( " -x Program asks for hexadecimal input. Following parameters ignored.\n" );
printf( " All other parameters are treated like filenames. The CRC values\n" );
printf( " for each separate file will be calculated.\n" );
exit( 0 );
}
if ( ! strcmp( argv[1], "-a" ) || ! strcmp( argv[1], "-A" ) ) do_ascii = CRC_TRUE;
if ( ! strcmp( argv[1], "-x" ) || ! strcmp( argv[1], "-X" ) ) do_hex = CRC_TRUE;
if ( do_ascii || do_hex ) {
printf( "Input: " );
fgets( input_string, MAX_STRING_SIZE-1, stdin );
}
if ( do_ascii ) {
ptr = input_string;
while ( *ptr && *ptr != '\r' && *ptr != '\n' ) ptr++;
*ptr = 0;
}
if ( do_hex ) {
ptr = input_string;
dest = input_string;
while( *ptr && *ptr != '\r' && *ptr != '\n' ) {
if ( *ptr >= '0' && *ptr <= '9' ) *dest++ = (char) ( (*ptr) - '0' );
if ( *ptr >= 'A' && *ptr <= 'F' ) *dest++ = (char) ( (*ptr) - 'A' + 10 );
if ( *ptr >= 'a' && *ptr <= 'f' ) *dest++ = (char) ( (*ptr) - 'a' + 10 );
ptr++;
}
* dest = '\x80';
*(dest+1) = '\x80';
}
a = 1;
do {
crc_16 = 0;
crc_16_modbus = 0xffff;
crc_dnp = 0;
crc_sick = 0;
crc_ccitt_0000 = 0;
crc_ccitt_ffff = 0xffff;
crc_ccitt_1d0f = 0x1d0f;
crc_kermit = 0;
crc_32 = 0xffffffffL;
if ( do_ascii ) {
prev_byte = 0;
ptr = input_string;
while ( *ptr ) {
crc_16 = update_crc_16( crc_16, *ptr );
crc_16_modbus = update_crc_16( crc_16_modbus, *ptr );
crc_dnp = update_crc_dnp( crc_dnp, *ptr );
crc_sick = update_crc_sick( crc_sick, *ptr, prev_byte );
crc_ccitt_0000 = update_crc_ccitt( crc_ccitt_0000, *ptr );
crc_ccitt_ffff = update_crc_ccitt( crc_ccitt_ffff, *ptr );
crc_ccitt_1d0f = update_crc_ccitt( crc_ccitt_1d0f, *ptr );
crc_kermit = update_crc_kermit( crc_kermit, *ptr );
crc_32 = update_crc_32( crc_32, *ptr );
prev_byte = *ptr;
ptr++;
}
}
else if ( do_hex ) {
prev_byte = 0;
ptr = input_string;
while ( *ptr != '\x80' ) {
hex_val = (char) ( ( * ptr & '\x0f' ) << 4 );
hex_val |= (char) ( ( *(ptr+1) & '\x0f' ) );
crc_16 = update_crc_16( crc_16, hex_val );
crc_16_modbus = update_crc_16( crc_16_modbus, hex_val );
crc_dnp = update_crc_dnp( crc_dnp, hex_val );
crc_sick = update_crc_sick( crc_sick, hex_val, prev_byte );
crc_ccitt_0000 = update_crc_ccitt( crc_ccitt_0000, hex_val );
crc_ccitt_ffff = update_crc_ccitt( crc_ccitt_ffff, hex_val );
crc_ccitt_1d0f = update_crc_ccitt( crc_ccitt_1d0f, hex_val );
crc_kermit = update_crc_kermit( crc_kermit, hex_val );
crc_32 = update_crc_32( crc_32, hex_val );
prev_byte = hex_val;
ptr += 2;
}
input_string[0] = 0;
}
else {
prev_byte = 0;
fp = fopen( argv[a], "rb" );
if ( fp != nullptr ) {
while( ( ch=fgetc( fp ) ) != EOF ) {
crc_16 = update_crc_16( crc_16, (char) ch );
crc_16_modbus = update_crc_16( crc_16_modbus, (char) ch );
crc_dnp = update_crc_dnp( crc_dnp, (char) ch );
crc_sick = update_crc_sick( crc_sick, (char) ch, prev_byte );
crc_ccitt_0000 = update_crc_ccitt( crc_ccitt_0000, (char) ch );
crc_ccitt_ffff = update_crc_ccitt( crc_ccitt_ffff, (char) ch );
crc_ccitt_1d0f = update_crc_ccitt( crc_ccitt_1d0f, (char) ch );
crc_kermit = update_crc_kermit( crc_kermit, (char) ch );
crc_32 = update_crc_32( crc_32, (char) ch );
prev_byte = (char) ch;
}
fclose( fp );
}
else printf( "%s : cannot open file\n", argv[a] );
}
crc_32 ^= 0xffffffffL;
crc_dnp = ~crc_dnp;
low_byte = (crc_dnp & 0xff00) >> 8;
high_byte = (crc_dnp & 0x00ff) << 8;
crc_dnp = low_byte | high_byte;
low_byte = (crc_sick & 0xff00) >> 8;
high_byte = (crc_sick & 0x00ff) << 8;
crc_sick = low_byte | high_byte;
low_byte = (crc_kermit & 0xff00) >> 8;
high_byte = (crc_kermit & 0x00ff) << 8;
crc_kermit = low_byte | high_byte;
printf( "%s%s%s :\nCRC16 = 0x%04X / %u\n"
"CRC16 (Modbus) = 0x%04X / %u\n"
"CRC16 (Sick) = 0x%04X / %u\n"
"CRC-CCITT (0x0000) = 0x%04X / %u\n"
"CRC-CCITT (0xffff) = 0x%04X / %u\n"
"CRC-CCITT (0x1d0f) = 0x%04X / %u\n"
"CRC-CCITT (Kermit) = 0x%04X / %u\n"
"CRC-DNP = 0x%04X / %u\n"
"CRC32 = 0x%08lX / %lu\n"
, ( do_ascii || do_hex ) ? "\"" : ""
, ( ! do_ascii && ! do_hex ) ? argv[a] : input_string
, ( do_ascii || do_hex ) ? "\"" : ""
, crc_16, crc_16
, crc_16_modbus, crc_16_modbus
, crc_sick, crc_sick
, crc_ccitt_0000, crc_ccitt_0000
, crc_ccitt_ffff, crc_ccitt_ffff
, crc_ccitt_1d0f, crc_ccitt_1d0f
, crc_kermit, crc_kermit
, crc_dnp, crc_dnp
, crc_32, crc_32 );
a++;
} while ( a < argc );
} /* main (tst_crc.c) */
| c |
fprime | data/projects/fprime/Utils/Hash/libcrc/lib_crc.c | #include "lib_crc.h"
/*******************************************************************\
* *
* Library : lib_crc *
* File : lib_crc.c *
* Author : Lammert Bies 1999-2008 *
* E-mail : [email protected] *
* Language : ANSI C *
* *
* *
* Description *
* =========== *
* *
* The file lib_crc.c contains the private and public func- *
* tions used for the calculation of CRC-16, CRC-CCITT and *
* CRC-32 cyclic redundancy values. *
* *
* *
* Dependencies *
* ============ *
* *
* lib_crc.h CRC definitions and prototypes *
* *
* *
* Modification history *
* ==================== *
* *
* Date Version Comment *
* *
* 2008-04-20 1.16 Added CRC-CCITT calculation for Kermit *
* *
* 2007-04-01 1.15 Added CRC16 calculation for Modbus *
* *
* 2007-03-28 1.14 Added CRC16 routine for Sick devices *
* *
* 2005-12-17 1.13 Added CRC-CCITT with initial 0x1D0F *
* *
* 2005-05-14 1.12 Added CRC-CCITT with start value 0 *
* *
* 2005-02-05 1.11 Fixed bug in CRC-DNP routine *
* *
* 2005-02-04 1.10 Added CRC-DNP routines *
* *
* 1999-02-21 1.01 Added FALSE and TRUE mnemonics *
* *
* 1999-01-22 1.00 Initial source *
* *
\*******************************************************************/
/*******************************************************************\
* *
* #define P_xxxx *
* *
* The CRC's are computed using polynomials. The coefficients *
* for the algorithms are defined by the following constants. *
* *
\*******************************************************************/
#define P_16 0xA001
#define P_32 0xEDB88320L
#define P_CCITT 0x1021
#define P_DNP 0xA6BC
#define P_KERMIT 0x8408
#define P_SICK 0x8005
/*******************************************************************\
* *
* static int crc_tab...init *
* static unsigned ... crc_tab...[] *
* *
* The algorithms use tables with precalculated values. This *
* speeds up the calculation dramatically. The first time the *
* CRC function is called, the table for that specific calcu- *
* lation is set up. The ...init variables are used to deter- *
* mine if the initialization has taken place. The calculated *
* values are stored in the crc_tab... arrays. *
* *
* The variables are declared static. This makes them invisi- *
* ble for other modules of the program. *
* *
\*******************************************************************/
static int crc_tab16_init = CRC_FALSE;
static int crc_tab32_init = CRC_FALSE;
static int crc_tabccitt_init = CRC_FALSE;
static int crc_tabdnp_init = CRC_FALSE;
static int crc_tabkermit_init = CRC_FALSE;
static unsigned short crc_tab16[256];
static unsigned long crc_tab32[256];
static unsigned short crc_tabccitt[256];
static unsigned short crc_tabdnp[256];
static unsigned short crc_tabkermit[256];
/*******************************************************************\
* *
* static void init_crc...tab(); *
* *
* Three local functions are used to initialize the tables *
* with values for the algorithm. *
* *
\*******************************************************************/
static void init_crc16_tab( void );
static void init_crc32_tab( void );
static void init_crcccitt_tab( void );
static void init_crcdnp_tab( void );
static void init_crckermit_tab( void );
/*******************************************************************\
* *
* unsigned short update_crc_ccitt( unsigned long crc, char c ); *
* *
* The function update_crc_ccitt calculates a new CRC-CCITT *
* value based on the previous value of the CRC and the next *
* byte of the data to be checked. *
* *
\*******************************************************************/
unsigned short update_crc_ccitt( unsigned short crc, char c ) {
unsigned short tmp, short_c;
short_c = 0x00ff & (unsigned short) c;
if ( ! crc_tabccitt_init ) init_crcccitt_tab();
tmp = (crc >> 8) ^ short_c;
crc = (unsigned short)((crc << 8) ^ crc_tabccitt[tmp]);
return crc;
} /* update_crc_ccitt */
/*******************************************************************\
* *
* unsigned short update_crc_sick( *
* unsigned long crc, char c, char prev_byte ); *
* *
* The function update_crc_sick calculates a new CRC-SICK *
* value based on the previous value of the CRC and the next *
* byte of the data to be checked. *
* *
\*******************************************************************/
unsigned short update_crc_sick( unsigned short crc, char c, char prev_byte ) {
unsigned short short_c, short_p;
short_c = 0x00ff & (unsigned short) c;
short_p = (unsigned short)(( 0x00ff & (unsigned short) prev_byte ) << 8);
if ( crc & 0x8000 ) crc = (unsigned short)(( crc << 1 ) ^ P_SICK);
else crc = (unsigned short)(crc << 1);
crc &= 0xffff;
crc ^= ( short_c | short_p );
return crc;
} /* update_crc_sick */
/*******************************************************************\
* *
* unsigned short update_crc_16( unsigned short crc, char c ); *
* *
* The function update_crc_16 calculates a new CRC-16 value *
* based on the previous value of the CRC and the next byte *
* of the data to be checked. *
* *
\*******************************************************************/
unsigned short update_crc_16( unsigned short crc, char c ) {
unsigned short tmp, short_c;
short_c = 0x00ff & (unsigned short) c;
if ( ! crc_tab16_init ) init_crc16_tab();
tmp = crc ^ short_c;
// Note: when masking by 0xff, range is limited to unsigned char
// which fits within unsigned int.
crc = (crc >> 8) ^ crc_tab16[ (unsigned int)(tmp & 0xff) ];
return crc;
} /* update_crc_16 */
/*******************************************************************\
* *
* unsigned short update_crc_kermit( unsigned short crc, char c ); *
* *
* The function update_crc_kermit calculates a new CRC value *
* based on the previous value of the CRC and the next byte *
* of the data to be checked. *
* *
\*******************************************************************/
unsigned short update_crc_kermit( unsigned short crc, char c ) {
unsigned short tmp, short_c;
short_c = 0x00ff & (unsigned short) c;
if ( ! crc_tabkermit_init ) init_crckermit_tab();
tmp = crc ^ short_c;
crc = (crc >> 8) ^ crc_tabkermit[ tmp & 0xff ];
return crc;
} /* update_crc_kermit */
/*******************************************************************\
* *
* unsigned short update_crc_dnp( unsigned short crc, char c ); *
* *
* The function update_crc_dnp calculates a new CRC-DNP value *
* based on the previous value of the CRC and the next byte *
* of the data to be checked. *
* *
\*******************************************************************/
unsigned short update_crc_dnp( unsigned short crc, char c ) {
unsigned short tmp, short_c;
short_c = 0x00ff & (unsigned short) c;
if ( ! crc_tabdnp_init ) init_crcdnp_tab();
tmp = crc ^ short_c;
crc = (crc >> 8) ^ crc_tabdnp[ tmp & 0xff ];
return crc;
} /* update_crc_dnp */
/*******************************************************************\
* *
* unsigned long update_crc_32( unsigned long crc, char c ); *
* *
* The function update_crc_32 calculates a new CRC-32 value *
* based on the previous value of the CRC and the next byte *
* of the data to be checked. *
* *
\*******************************************************************/
unsigned long update_crc_32( unsigned long crc, char c ) {
unsigned long tmp, long_c;
long_c = 0x000000ffL & (unsigned long) c;
if ( ! crc_tab32_init ) init_crc32_tab();
tmp = crc ^ long_c;
crc = (crc >> 8) ^ crc_tab32[ tmp & 0xff ];
return crc;
} /* update_crc_32 */
/*******************************************************************\
* *
* static void init_crc16_tab( void ); *
* *
* The function init_crc16_tab() is used to fill the array *
* for calculation of the CRC-16 with values. *
* *
\*******************************************************************/
static void init_crc16_tab( void ) {
int i, j;
unsigned short crc, c;
for (i=0; i<256; i++) {
crc = 0;
c = (unsigned short) i;
for (j=0; j<8; j++) {
if ( (crc ^ c) & 0x0001 ) crc = ( crc >> 1 ) ^ P_16;
else crc = crc >> 1;
c = c >> 1;
}
crc_tab16[i] = crc;
}
crc_tab16_init = CRC_TRUE;
} /* init_crc16_tab */
/*******************************************************************\
* *
* static void init_crckermit_tab( void ); *
* *
* The function init_crckermit_tab() is used to fill the array *
* for calculation of the CRC Kermit with values. *
* *
\*******************************************************************/
static void init_crckermit_tab( void ) {
int i, j;
unsigned short crc, c;
for (i=0; i<256; i++) {
crc = 0;
c = (unsigned short) i;
for (j=0; j<8; j++) {
if ( (crc ^ c) & 0x0001 ) crc = ( crc >> 1 ) ^ P_KERMIT;
else crc = crc >> 1;
c = c >> 1;
}
crc_tabkermit[i] = crc;
}
crc_tabkermit_init = CRC_TRUE;
} /* init_crckermit_tab */
/*******************************************************************\
* *
* static void init_crcdnp_tab( void ); *
* *
* The function init_crcdnp_tab() is used to fill the array *
* for calculation of the CRC-DNP with values. *
* *
\*******************************************************************/
static void init_crcdnp_tab( void ) {
int i, j;
unsigned short crc, c;
for (i=0; i<256; i++) {
crc = 0;
c = (unsigned short) i;
for (j=0; j<8; j++) {
if ( (crc ^ c) & 0x0001 ) crc = ( crc >> 1 ) ^ P_DNP;
else crc = crc >> 1;
c = c >> 1;
}
crc_tabdnp[i] = crc;
}
crc_tabdnp_init = CRC_TRUE;
} /* init_crcdnp_tab */
/*******************************************************************\
* *
* static void init_crc32_tab( void ); *
* *
* The function init_crc32_tab() is used to fill the array *
* for calculation of the CRC-32 with values. *
* *
\*******************************************************************/
static void init_crc32_tab( void ) {
int i, j;
unsigned long crc;
for (i=0; i<256; i++) {
crc = (unsigned long) i;
for (j=0; j<8; j++) {
if ( crc & 0x00000001L ) crc = ( crc >> 1 ) ^ P_32;
else crc = crc >> 1;
}
crc_tab32[i] = crc;
}
crc_tab32_init = CRC_TRUE;
} /* init_crc32_tab */
/*******************************************************************\
* *
* static void init_crcccitt_tab( void ); *
* *
* The function init_crcccitt_tab() is used to fill the array *
* for calculation of the CRC-CCITT with values. *
* *
\*******************************************************************/
static void init_crcccitt_tab( void ) {
int i, j;
unsigned short crc, c;
for (i=0; i<256; i++) {
crc = 0;
c = (unsigned short)(((unsigned short) i) << 8);
for (j=0; j<8; j++) {
if ( (crc ^ c) & 0x8000 ) crc = (unsigned short)(( crc << 1 ) ^ P_CCITT);
else crc = (unsigned short)(crc << 1);
c = (unsigned short)(c << 1);
}
crc_tabccitt[i] = crc;
}
crc_tabccitt_init = CRC_TRUE;
} /* init_crcccitt_tab */
| c |
fprime | data/projects/fprime/Utils/Types/CircularBuffer.hpp | /*
* CircularBuffer.hpp:
*
* Buffer used to efficiently store data in ring data structure. Uses an externally supplied
* data store as the backing for this buffer. Thus it is dependent on receiving sole ownership
* of the supplied buffer.
*
* Note: this given implementation loses one byte of the data store in order to ensure that a
* separate wrap-around tracking variable is not needed.
*
* Created on: Apr 4, 2019
* Author: lestarch
* Revised March 2022
* Author: bocchino
*/
#ifndef TYPES_CIRCULAR_BUFFER_HPP
#define TYPES_CIRCULAR_BUFFER_HPP
#include <FpConfig.hpp>
#include <Fw/Types/Serializable.hpp>
//#define CIRCULAR_DEBUG
namespace Types {
class CircularBuffer {
public:
/**
* Circular buffer constructor. Wraps the supplied buffer as the new data store. Buffer
* size is supplied in the 'size' argument.
*
* Note: specification of storage buffer must be done using `setup` before use.
*/
CircularBuffer();
/**
* Circular buffer constructor. Wraps the supplied buffer as the new data store. Buffer
* size is supplied in the 'size' argument. This is equivalent to calling the no-argument constructor followed
* by setup(buffer, size).
*
* Note: ownership of the supplied buffer is held until the circular buffer is deallocated
*
* \param buffer: supplied buffer used as a data store.
* \param size: the of the supplied data store.
*/
CircularBuffer(U8* const buffer, const NATIVE_UINT_TYPE size);
/**
* Wraps the supplied buffer as the new data store. Buffer size is supplied in the 'size' argument. Cannot be
* called after successful setup.
*
* Note: ownership of the supplied buffer is held until the circular buffer is deallocated
*
* \param buffer: supplied buffer used as a data store.
* \param size: the of the supplied data store.
*/
void setup(U8* const buffer, const NATIVE_UINT_TYPE size);
/**
* Serialize a given buffer into this circular buffer. Will not accept more data than
* space available. This means it will not overwrite existing data.
* \param buffer: supplied buffer to be serialized.
* \param size: size of the supplied buffer.
* \return Fw::FW_SERIALIZE_OK on success or something else on error
*/
Fw::SerializeStatus serialize(const U8* const buffer, const NATIVE_UINT_TYPE size);
/**
* Deserialize data into the given variable without moving the head index
* \param value: value to fill
* \param offset: offset from head to start peak. Default: 0
* \return Fw::FW_SERIALIZE_OK on success or something else on error
*/
Fw::SerializeStatus peek(char& value, NATIVE_UINT_TYPE offset = 0) const;
/**
* Deserialize data into the given variable without moving the head index
* \param value: value to fill
* \param offset: offset from head to start peak. Default: 0
* \return Fw::FW_SERIALIZE_OK on success or something else on error
*/
Fw::SerializeStatus peek(U8& value, NATIVE_UINT_TYPE offset = 0) const;
/**
* Deserialize data into the given variable without moving the head index
* \param value: value to fill
* \param offset: offset from head to start peak. Default: 0
* \return Fw::FW_SERIALIZE_OK on success or something else on error
*/
Fw::SerializeStatus peek(U32& value, NATIVE_UINT_TYPE offset = 0) const;
/**
* Deserialize data into the given buffer without moving the head variable.
* \param buffer: buffer to fill with data of the peek
* \param size: size in bytes to peek at
* \param offset: offset from head to start peak. Default: 0
* \return Fw::FW_SERIALIZE_OK on success or something else on error
*/
Fw::SerializeStatus peek(U8* buffer, NATIVE_UINT_TYPE size, NATIVE_UINT_TYPE offset = 0) const;
/**
* Rotate the head index, deleting data from the circular buffer and making
* space. Cannot rotate more than the available space.
* \param amount: amount to rotate by (in bytes)
* \return Fw::FW_SERIALIZE_OK on success or something else on error
*/
Fw::SerializeStatus rotate(NATIVE_UINT_TYPE amount);
/**
* Get the number of bytes allocated in the buffer
* \return number of bytes
*/
NATIVE_UINT_TYPE get_allocated_size() const;
/**
* Get the number of free bytes, i.e., the number
* of bytes that may be stored in the buffer without
* deleting data and without exceeding the buffer capacity
*/
NATIVE_UINT_TYPE get_free_size() const;
/**
* Get the logical capacity of the buffer, i.e., the number of available
* bytes when the buffer is empty
*/
NATIVE_UINT_TYPE get_capacity() const;
/**
* Return the largest tracked allocated size
*/
NATIVE_UINT_TYPE get_high_water_mark() const;
/**
* Clear tracking of the largest allocated size
*/
void clear_high_water_mark();
#ifdef CIRCULAR_DEBUG
void print();
#endif
PRIVATE:
/**
* Returns a wrap-advanced index into the store.
* \param idx: index to advance and wrap.
* \param amount: amount to advance
* \return: new index value
*/
NATIVE_UINT_TYPE advance_idx(NATIVE_UINT_TYPE idx, NATIVE_UINT_TYPE amount = 1) const;
//! Physical store backing this circular buffer
U8* m_store;
//! Size of the physical store
NATIVE_UINT_TYPE m_store_size;
//! Index into m_store of byte zero in the logical store.
//! When memory is deallocated, this index moves forward and wraps around.
NATIVE_UINT_TYPE m_head_idx;
//! Allocated size (size of the logical store)
NATIVE_UINT_TYPE m_allocated_size;
//! Maximum allocated size
NATIVE_UINT_TYPE m_high_water_mark;
};
} //End Namespace Types
#endif
| hpp |
fprime | data/projects/fprime/Utils/Types/Queue.cpp | /*
* Queue.cpp:
*
* Implementation of the queue data type.
*
* Created on: July 5th, 2022
* Author: lestarch
*
*/
#include "Queue.hpp"
#include <Fw/Types/Assert.hpp>
namespace Types {
Queue::Queue() : m_internal(), m_message_size(0) {}
void Queue::setup(U8* const storage, const FwSizeType storage_size, const FwSizeType depth, const FwSizeType message_size) {
// Ensure that enough storage was supplied
const FwSizeType total_needed_size = depth * message_size;
FW_ASSERT(storage_size >= total_needed_size, storage_size, depth, message_size);
m_internal.setup(storage, total_needed_size);
m_message_size = message_size;
}
Fw::SerializeStatus Queue::enqueue(const U8* const message, const FwSizeType size) {
FW_ASSERT(m_message_size > 0, m_message_size); // Ensure initialization
FW_ASSERT(m_message_size == size, size, m_message_size); // Message size is as expected
return m_internal.serialize(message, static_cast<NATIVE_UINT_TYPE>(m_message_size));
}
Fw::SerializeStatus Queue::dequeue(U8* const message, const FwSizeType size) {
FW_ASSERT(m_message_size > 0); // Ensure initialization
FW_ASSERT(m_message_size <= size, size, m_message_size); // Sufficient storage space for read message
Fw::SerializeStatus result = m_internal.peek(message, static_cast<NATIVE_UINT_TYPE>(m_message_size), 0);
if (result != Fw::FW_SERIALIZE_OK) {
return result;
}
return m_internal.rotate(m_message_size);
}
NATIVE_UINT_TYPE Queue::get_high_water_mark() const {
FW_ASSERT(m_message_size > 0, m_message_size);
return m_internal.get_high_water_mark() / m_message_size;
}
void Queue::clear_high_water_mark() {
m_internal.clear_high_water_mark();
}
NATIVE_UINT_TYPE Queue::getQueueSize() const {
FW_ASSERT(m_message_size > 0, m_message_size);
return m_internal.get_allocated_size()/m_message_size;
}
} // namespace Types | cpp |
fprime | data/projects/fprime/Utils/Types/Queue.hpp | /*
* Queue.hpp:
*
* FIFO queue of fixed size messages. For use generally where non-concurrent, non-OS backed based FIFO queues are
* necessary. Message size is defined at construction time and all messages enqueued and dequeued must be of that fixed
* size. Wraps circular buffer to perform actual storage of messages. This implementation is not thread safe and the
* expectation is that the user will wrap it in concurrency constructs where necessary.
*
* Created on: July 5th, 2022
* Author: lestarch
*
*/
#ifndef _UTILS_TYPES_QUEUE_HPP
#define _UTILS_TYPES_QUEUE_HPP
#include <FpConfig.hpp>
#include <Fw/Types/BasicTypes.hpp>
#include <Fw/Types/Serializable.hpp>
#include <Utils/Types/CircularBuffer.hpp>
namespace Types {
class Queue {
public:
/**
* \brief constructs an uninitialized queue
*/
Queue();
/**
* \brief setup the queue object to setup storage
*
* The queue must be configured before use to setup storage parameters. This function supplies those parameters
* including depth, and message size. Storage size must be greater than or equal to the depth x message size.
*
* \param storage: storage memory allocation
* \param storage_size: size of the provided allocation
* \param depth: depth of the queue
* \param message_size: size of individual messages
*/
void setup(U8* const storage, const FwSizeType storage_size, const FwSizeType depth, const FwSizeType message_size);
/**
* \brief pushes a fixed-size message onto the back of the queue
*
* Pushes a fixed-size message onto the queue. This performs a copy of the data onto the queue so the user is free
* to dispose the message data as soon as the call returns. Note: message is required to be of the size message_size
* as defined by the construction of the queue. Size is provided as a safety check to ensure the sent size is
* consistent with the expected size of the queue.
*
* This will return a non-Fw::SERIALIZE_OK status when the queue is full.
*
* \param message: message of size m_message_size to enqueue
* \param size: size of the message being sent. Must be equivalent to queue's message size.
* \return: Fw::SERIALIZE_OK on success, something else on failure
*/
Fw::SerializeStatus enqueue(const U8* const message, const FwSizeType size);
/**
* \brief pops a fixed-size message off the front of the queue
*
* Pops a fixed-size message off the front of the queue. This performs a copy of the data into the provided message
* buffer. Note: message is required to be of the size message_size as defined by the construction of the queue. The
* size must be greater or equal to message size, although only message size bytes will be used.
*
* This will return a non-Fw::SERIALIZE_OK status when the queue is empty.
*
* \param message: message of size m_message_size to dequeue
* \param size: size of the buffer being supplied.
* \return: Fw::SERIALIZE_OK on success, something else on failure
*/
Fw::SerializeStatus dequeue(U8* const message, const FwSizeType size);
/**
* Return the largest tracked allocated size
*/
NATIVE_UINT_TYPE get_high_water_mark() const;
/**
* Clear tracking of the largest allocated size
*/
void clear_high_water_mark();
NATIVE_UINT_TYPE getQueueSize() const;
private:
CircularBuffer m_internal;
FwSizeType m_message_size;
};
} // namespace Types
#endif // _UTILS_TYPES_QUEUE_HPP
| hpp |
fprime | data/projects/fprime/Utils/Types/CircularBuffer.cpp | /*
* CircularBuffer.cpp:
*
* Buffer used to efficiently store data in ring data structure. Uses an externally supplied
* data store as the backing for this buffer. Thus it is dependent on receiving sole ownership
* of the supplied buffer.
*
* This implementation file contains the function definitions.
*
* Created on: Apr 4, 2019
* Author: lestarch
* Revised March 2022
* Author: bocchino
*/
#include <FpConfig.hpp>
#include <Fw/Types/Assert.hpp>
#include <Utils/Types/CircularBuffer.hpp>
#ifdef CIRCULAR_DEBUG
#include <Os/Log.hpp>
#endif
namespace Types {
CircularBuffer :: CircularBuffer() :
m_store(nullptr),
m_store_size(0),
m_head_idx(0),
m_allocated_size(0),
m_high_water_mark(0)
{
}
CircularBuffer :: CircularBuffer(U8* const buffer, const NATIVE_UINT_TYPE size) :
m_store(nullptr),
m_store_size(0),
m_head_idx(0),
m_allocated_size(0),
m_high_water_mark(0)
{
setup(buffer, size);
}
void CircularBuffer :: setup(U8* const buffer, const NATIVE_UINT_TYPE size) {
FW_ASSERT(size > 0);
FW_ASSERT(buffer != nullptr);
FW_ASSERT(m_store == nullptr && m_store_size == 0); // Not already setup
// Initialize buffer data
m_store = buffer;
m_store_size = size;
m_head_idx = 0;
m_allocated_size = 0;
m_high_water_mark = 0;
}
NATIVE_UINT_TYPE CircularBuffer :: get_allocated_size() const {
return m_allocated_size;
}
NATIVE_UINT_TYPE CircularBuffer :: get_free_size() const {
FW_ASSERT(m_store != nullptr && m_store_size != 0); // setup method was called
FW_ASSERT(m_allocated_size <= m_store_size, m_allocated_size);
return m_store_size - m_allocated_size;
}
NATIVE_UINT_TYPE CircularBuffer :: advance_idx(NATIVE_UINT_TYPE idx, NATIVE_UINT_TYPE amount) const {
FW_ASSERT(idx < m_store_size, idx);
return (idx + amount) % m_store_size;
}
Fw::SerializeStatus CircularBuffer :: serialize(const U8* const buffer, const NATIVE_UINT_TYPE size) {
FW_ASSERT(m_store != nullptr && m_store_size != 0); // setup method was called
FW_ASSERT(buffer != nullptr);
// Check there is sufficient space
if (size > get_free_size()) {
return Fw::FW_SERIALIZE_NO_ROOM_LEFT;
}
// Copy in all the supplied data
NATIVE_UINT_TYPE idx = advance_idx(m_head_idx, m_allocated_size);
for (U32 i = 0; i < size; i++) {
FW_ASSERT(idx < m_store_size, idx);
m_store[idx] = buffer[i];
idx = advance_idx(idx);
}
m_allocated_size += size;
FW_ASSERT(m_allocated_size <= this->get_capacity(), m_allocated_size);
m_high_water_mark = (m_high_water_mark > m_allocated_size) ? m_high_water_mark : m_allocated_size;
return Fw::FW_SERIALIZE_OK;
}
Fw::SerializeStatus CircularBuffer :: peek(char& value, NATIVE_UINT_TYPE offset) const {
FW_ASSERT(m_store != nullptr && m_store_size != 0); // setup method was called
return peek(reinterpret_cast<U8&>(value), offset);
}
Fw::SerializeStatus CircularBuffer :: peek(U8& value, NATIVE_UINT_TYPE offset) const {
FW_ASSERT(m_store != nullptr && m_store_size != 0); // setup method was called
// Check there is sufficient data
if ((sizeof(U8) + offset) > m_allocated_size) {
return Fw::FW_DESERIALIZE_BUFFER_EMPTY;
}
const NATIVE_UINT_TYPE idx = advance_idx(m_head_idx, offset);
FW_ASSERT(idx < m_store_size, idx);
value = m_store[idx];
return Fw::FW_SERIALIZE_OK;
}
Fw::SerializeStatus CircularBuffer :: peek(U32& value, NATIVE_UINT_TYPE offset) const {
FW_ASSERT(m_store != nullptr && m_store_size != 0); // setup method was called
// Check there is sufficient data
if ((sizeof(U32) + offset) > m_allocated_size) {
return Fw::FW_DESERIALIZE_BUFFER_EMPTY;
}
value = 0;
NATIVE_UINT_TYPE idx = advance_idx(m_head_idx, offset);
// Deserialize all the bytes from network format
for (NATIVE_UINT_TYPE i = 0; i < sizeof(U32); i++) {
FW_ASSERT(idx < m_store_size, idx);
value = (value << 8) | static_cast<U32>(m_store[idx]);
idx = advance_idx(idx);
}
return Fw::FW_SERIALIZE_OK;
}
Fw::SerializeStatus CircularBuffer :: peek(U8* buffer, NATIVE_UINT_TYPE size, NATIVE_UINT_TYPE offset) const {
FW_ASSERT(m_store != nullptr && m_store_size != 0); // setup method was called
FW_ASSERT(buffer != nullptr);
// Check there is sufficient data
if ((size + offset) > m_allocated_size) {
return Fw::FW_DESERIALIZE_BUFFER_EMPTY;
}
NATIVE_UINT_TYPE idx = advance_idx(m_head_idx, offset);
// Deserialize all the bytes from network format
for (NATIVE_UINT_TYPE i = 0; i < size; i++) {
FW_ASSERT(idx < m_store_size, idx);
buffer[i] = m_store[idx];
idx = advance_idx(idx);
}
return Fw::FW_SERIALIZE_OK;
}
Fw::SerializeStatus CircularBuffer :: rotate(NATIVE_UINT_TYPE amount) {
FW_ASSERT(m_store != nullptr && m_store_size != 0); // setup method was called
// Check there is sufficient data
if (amount > m_allocated_size) {
return Fw::FW_DESERIALIZE_BUFFER_EMPTY;
}
m_head_idx = advance_idx(m_head_idx, amount);
m_allocated_size -= amount;
return Fw::FW_SERIALIZE_OK;
}
NATIVE_UINT_TYPE CircularBuffer ::get_capacity() const {
FW_ASSERT(m_store != nullptr && m_store_size != 0); // setup method was called
return m_store_size;
}
NATIVE_UINT_TYPE CircularBuffer ::get_high_water_mark() const {
return m_high_water_mark;
}
void CircularBuffer ::clear_high_water_mark() {
m_high_water_mark = 0;
}
#ifdef CIRCULAR_DEBUG
void CircularBuffer :: print() {
NATIVE_UINT_TYPE idx = m_head_idx;
Os::Log::logMsg("Ring: ", 0, 0, 0, 0, 0, 0);
for (NATIVE_UINT_TYPE i = 0; i < m_allocated_size; ++i) {
Os::Log::logMsg("%c", m_store[idx], 0, 0, 0, 0, 0);
idx = advance_idx(idx);
}
Os::Log::logMsg("\n", 0, 0, 0, 0, 0, 0);
}
#endif
} //End Namespace Types
| cpp |
fprime | data/projects/fprime/Utils/Types/test/ut/CircularBuffer/CircularRules.cpp | /**
* CircularRules.cpp:
*
* This file specifies Rule classes for testing of the Types::CircularRules. These rules can then be used by the main
* testing program to test the code.
*
*
* @author mstarch
*/
#include "CircularRules.hpp"
#include <cstdlib>
#include <cmath>
namespace Types {
RandomizeRule::RandomizeRule(const char *const name)
: STest::Rule<MockTypes::CircularState>(name) {}
bool RandomizeRule::precondition(const MockTypes::CircularState& state) {
return true;
}
void RandomizeRule::action(MockTypes::CircularState& truth) {
(void) truth.generateRandomBuffer();
}
SerializeOkRule::SerializeOkRule(const char *const name)
: STest::Rule<MockTypes::CircularState>(name) {}
bool SerializeOkRule::precondition(const MockTypes::CircularState& state) {
return state.getRemainingSize() >= state.getRandomSize();
}
void SerializeOkRule::action(MockTypes::CircularState& state) {
state.checkSizes();
Fw::SerializeStatus status = state.getTestBuffer().serialize(state.getBuffer(), state.getRandomSize());
state.setRemainingSize(state.getRemainingSize() - state.getRandomSize());
ASSERT_TRUE(state.addInfinite(state.getBuffer(), state.getRandomSize()));
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK);
state.checkSizes();
}
SerializeOverflowRule::SerializeOverflowRule(const char *const name)
: STest::Rule<MockTypes::CircularState>(name) {}
bool SerializeOverflowRule::precondition(const MockTypes::CircularState& state) {
return state.getRemainingSize() < state.getRandomSize();
}
void SerializeOverflowRule::action(MockTypes::CircularState& state) {
Fw::SerializeStatus status = state.getTestBuffer().serialize(state.getBuffer(), state.getRandomSize());
ASSERT_EQ(status, Fw::FW_SERIALIZE_NO_ROOM_LEFT);
}
PeekOkRule::PeekOkRule(const char *const name)
: STest::Rule<MockTypes::CircularState>(name) {}
bool PeekOkRule::precondition(const MockTypes::CircularState& state) {
NATIVE_UINT_TYPE peek_available = (MAX_BUFFER_SIZE - state.getRemainingSize());
if (state.getPeekType() == 0 ) {
return peek_available >= sizeof(I8) + state.getPeekOffset();
}
else if (state.getPeekType() == 1) {
return peek_available >= sizeof(U8) + state.getPeekOffset();
}
else if (state.getPeekType() == 2) {
return peek_available >= sizeof(U32) + state.getPeekOffset();
}
else if (state.getPeekType() == 3) {
return peek_available >= state.getRandomSize() + state.getPeekOffset();
}
return false;
}
void PeekOkRule::action(MockTypes::CircularState& state) {
U8* buffer = nullptr;
char peek_char = 0;
U8 peek_u8 = 0;
U32 peek_u32 = 0;
U8 peek_buffer[MAX_BUFFER_SIZE];
// Handle all cases for deserialization
if (state.getPeekType() == 0) {
ASSERT_TRUE(state.peek(buffer, sizeof(I8), state.getPeekOffset()));
peek_char = static_cast<char>(buffer[0]);
ASSERT_EQ(state.getTestBuffer().peek(peek_char, state.getPeekOffset()), Fw::FW_SERIALIZE_OK);
ASSERT_EQ(static_cast<char>(buffer[0]), peek_char);
}
else if (state.getPeekType() == 1) {
ASSERT_TRUE(state.peek(buffer, sizeof(U8), state.getPeekOffset()));
peek_u8 = static_cast<U8>(buffer[0]);
ASSERT_EQ(state.getTestBuffer().peek(peek_u8, state.getPeekOffset()), Fw::FW_SERIALIZE_OK);
ASSERT_EQ(buffer[0], peek_u8);
}
else if (state.getPeekType() == 2) {
ASSERT_TRUE(state.peek(buffer, sizeof(U32), state.getPeekOffset()));
ASSERT_EQ(state.getTestBuffer().peek(peek_u32, state.getPeekOffset()), Fw::FW_SERIALIZE_OK);
// Big-endian U32
U32 value = 0;
value |= (buffer[0] << 24);
value |= (buffer[1] << 16);
value |= (buffer[2] << 8);
value |= (buffer[3] << 0);
ASSERT_EQ(value, peek_u32);
}
else if (state.getPeekType() == 3) {
ASSERT_TRUE(state.peek(buffer, state.getRandomSize(), state.getPeekOffset()));
ASSERT_EQ(state.getTestBuffer().peek(peek_buffer, state.getRandomSize(), state.getPeekOffset()),
Fw::FW_SERIALIZE_OK);
for (NATIVE_UINT_TYPE i = 0; i < state.getRandomSize(); i++) {
ASSERT_EQ(buffer[i], peek_buffer[i]);
}
}
else {
ASSERT_TRUE(false); // Fail the test, bad type
}
}
PeekBadRule::PeekBadRule(const char *const name)
: STest::Rule<MockTypes::CircularState>(name) {}
bool PeekBadRule::precondition(const MockTypes::CircularState& state) {
NATIVE_UINT_TYPE peek_available = (MAX_BUFFER_SIZE - state.getRemainingSize());
if (state.getPeekType() == 0 ) {
return peek_available < sizeof(I8) + state.getPeekOffset();
}
else if (state.getPeekType() == 1) {
return peek_available < sizeof(U8) + state.getPeekOffset();
}
else if (state.getPeekType() == 2) {
return peek_available < sizeof(U32) + state.getPeekOffset();
}
else if (state.getPeekType() == 3) {
return peek_available < state.getRandomSize() + state.getPeekOffset();
}
return false;
}
void PeekBadRule::action(MockTypes::CircularState& state) {
char peek_char = 0;
U8 peek_u8 = 0;
U32 peek_u32 = 0;
U8 peek_buffer[MAX_BUFFER_SIZE];
// Handle all cases for deserialization
if (state.getPeekType() == 0) {
ASSERT_EQ(state.getTestBuffer().peek(peek_char, state.getPeekOffset()), Fw::FW_DESERIALIZE_BUFFER_EMPTY);
}
else if (state.getPeekType() == 1) {
ASSERT_EQ(state.getTestBuffer().peek(peek_u8, state.getPeekOffset()), Fw::FW_DESERIALIZE_BUFFER_EMPTY);
}
else if (state.getPeekType() == 2) {
ASSERT_EQ(state.getTestBuffer().peek(peek_u32, state.getPeekOffset()), Fw::FW_DESERIALIZE_BUFFER_EMPTY);
}
else if (state.getPeekType() == 3) {
ASSERT_EQ(state.getTestBuffer().peek(peek_buffer, state.getRandomSize(), state.getPeekOffset()),
Fw::FW_DESERIALIZE_BUFFER_EMPTY);
}
else {
ASSERT_TRUE(false); // Fail the test, bad type
}
}
RotateOkRule::RotateOkRule(const char *const name)
: STest::Rule<MockTypes::CircularState>(name) {}
bool RotateOkRule::precondition(const MockTypes::CircularState& state) {
NATIVE_UINT_TYPE rotate_available = (MAX_BUFFER_SIZE - state.getRemainingSize());
return rotate_available >= state.getRandomSize();
}
void RotateOkRule::action(MockTypes::CircularState& state) {
state.checkSizes();
ASSERT_EQ(state.getTestBuffer().rotate(state.getRandomSize()), Fw::FW_SERIALIZE_OK);
ASSERT_TRUE(state.rotate(state.getRandomSize()));
state.setRemainingSize(state.getRemainingSize() + state.getRandomSize());
state.checkSizes();
}
RotateBadRule::RotateBadRule(const char *const name)
: STest::Rule<MockTypes::CircularState>(name) {}
bool RotateBadRule::precondition(const MockTypes::CircularState& state) {
NATIVE_UINT_TYPE rotate_available = (MAX_BUFFER_SIZE - state.getRemainingSize());
return rotate_available < state.getRandomSize();
}
void RotateBadRule::action(MockTypes::CircularState& state) {
ASSERT_EQ(state.getTestBuffer().rotate(state.getRandomSize()), Fw::FW_DESERIALIZE_BUFFER_EMPTY);
}
};
| cpp |
fprime | data/projects/fprime/Utils/Types/test/ut/CircularBuffer/Main.cpp | /**
* Main.cpp:
*
* Setup the GTests for rules-based testing runs these tests.
*
* Created on: May 23, 2019
* Author: mstarch
*/
#include <STest/Scenario/Scenario.hpp>
#include <STest/Scenario/RandomScenario.hpp>
#include <STest/Scenario/BoundedScenario.hpp>
#include <Fw/Test/UnitTest.hpp>
#include <Utils/Types/test/ut/CircularBuffer/CircularRules.hpp>
#include <gtest/gtest.h>
#include <cstdio>
#include <cmath>
#define STEP_COUNT 1000
/**
* A random hopper for rules. Apply STEP_COUNT times.
*/
TEST(CircularBufferTests, RandomCircularTests) {
F64 max_addr_mem = sizeof(NATIVE_UINT_TYPE) * 8.0;
max_addr_mem = pow(2.0, max_addr_mem);
// Ensure the maximum memory use is less that the max addressable memory
F64 max_used_mem = static_cast<double>(STEP_COUNT) * static_cast<double>(MAX_BUFFER_SIZE);
ASSERT_LT(max_used_mem, max_addr_mem);
MockTypes::CircularState state;
// Create rules, and assign them into the array
Types::RandomizeRule randomize("Randomize");
Types::SerializeOkRule serializeOk("SerializeOk");
Types::SerializeOverflowRule serializeOverflow("serializeOverflow");
Types::PeekOkRule peekOk("peekOk");
Types::PeekBadRule peekBad("peekBad");
Types::PeekOkRule rotateOk("rotateOk");
Types::PeekBadRule rotateBad("rotateBad");
// Setup a list of rules to choose from
STest::Rule<MockTypes::CircularState>* rules[] = {
&randomize,
&serializeOk,
&serializeOverflow,
&peekOk,
&peekBad,
&rotateOk,
&rotateBad
};
// Construct the random scenario and run it with the defined bounds
STest::RandomScenario<MockTypes::CircularState> random("Random Rules", rules,
FW_NUM_ARRAY_ELEMENTS(rules));
// Setup a bounded scenario to run rules a set number of times
STest::BoundedScenario<MockTypes::CircularState> bounded("Bounded Random Rules Scenario",
random, STEP_COUNT);
// Run!
const U32 numSteps = bounded.run(state);
printf("Ran %u steps.\n", numSteps);
}
/**
* Test that the most basic logging function works.
*/
TEST(CircularBufferTests, BasicSerializeTest) {
// Setup and register state
MockTypes::CircularState state;
// Create rules, and assign them into the array
Types::RandomizeRule randomGo("randomGo");
Types::SerializeOkRule serializeOk("SerializeOk");
randomGo.apply(state);
serializeOk.apply(state);
}
/**
* Test that the most basic circular overflow.
*/
TEST(CircularBufferTests, BasicOverflowTest) {
// Setup state and fill it with garbage
MockTypes::CircularState state;
ASSERT_EQ(Fw::FW_SERIALIZE_OK , state.getTestBuffer().serialize(state.getBuffer(), state.getRandomSize()));
state.setRemainingSize(0);
// Create rules, and assign them into the array
Types::RandomizeRule randomGo("randomGo");
Types::SerializeOverflowRule serializeOverflow("serializeOverflow");
randomGo.apply(state);
serializeOverflow.apply(state);
}
/**
* Test that the most basic peeks work.
*/
TEST(CircularBufferTests, BasicPeekTest) {
char peek_char = 0x85;
U8 peek_u8 = 0x95;
U32 peek_u32 = 0xdeadc0de;
U8 buffer[1024] = {}; // Clear out memory to appease valgrind
// Setup all circular state
MockTypes::CircularState state;
state.addInfinite(reinterpret_cast<U8*>(&peek_char), sizeof(peek_char));
state.getTestBuffer().serialize(reinterpret_cast<U8*>(&peek_char), sizeof(peek_char));
state.addInfinite(&peek_u8, sizeof(peek_u8));
state.getTestBuffer().serialize(&peek_u8, sizeof(peek_u8));
for (NATIVE_UINT_TYPE i = sizeof(U32); i > 0; i--) {
U8 byte = peek_u32 >> ((i - 1) * 8);
state.addInfinite(&byte, sizeof(byte));
state.getTestBuffer().serialize(&byte, sizeof(byte));
}
state.addInfinite(buffer, sizeof(buffer));
state.getTestBuffer().serialize(buffer, sizeof(buffer));
state.setRemainingSize(MAX_BUFFER_SIZE - 1030);
// Run all peek variants
Types::PeekOkRule peekOk("peekOk");
state.setRandom(0, 0, 0);
peekOk.apply(state);
state.setRandom(0, 1, 1);
peekOk.apply(state);
state.setRandom(0, 2, 2);
peekOk.apply(state);
state.setRandom(sizeof(buffer), 3, 6);
peekOk.apply(state);
}
/**
* Test that the most basic bad-peeks work.
*/
TEST(CircularBufferTests, BasicPeekBadTest) {
// Setup all circular state
MockTypes::CircularState state;
// Run all peek variants
Types::PeekBadRule peekBad("peekBad");
state.setRandom(0, 0, 0);
peekBad.apply(state);
state.setRandom(0, 1, 1);
peekBad.apply(state);
state.setRandom(0, 2, 2);
peekBad.apply(state);
state.setRandom(1024, 3, 6);
peekBad.apply(state);
}
/**
* Test that the most basic rotate work.
*/
TEST(CircularBufferTests, BasicRotateTest) {
// Setup and register state
MockTypes::CircularState state;
// Create rules, and assign them into the array
Types::RandomizeRule randomGo("randomGo");
Types::SerializeOkRule serializeOk("SerializeOk");
Types::RotateOkRule rotateOk("rotateOk");
randomGo.apply(state);
serializeOk.apply(state);
rotateOk.apply(state);
}
/**
* Test that the most basic bad-rotate work.
*/
TEST(CircularBufferTests, BasicRotateBadTest) {
// Setup all circular state
MockTypes::CircularState state;
// Run all peek variants
Types::RotateBadRule rotateBad("rotateBad");
rotateBad.apply(state);
}
/**
* Test boundary cases
*/
TEST(CircularBufferTests, BoundaryCases) {
MockTypes::CircularState state;
// Serialize an empty buffer
state.setRandom(0, 0, 0);
Types::SerializeOkRule serializeOk("serializeOk");
serializeOk.apply(state);
// Serialize a max size buffer
state.setRandom(MAX_BUFFER_SIZE, 0, 0);
serializeOk.apply(state);
}
int main(int argc, char* argv[]) {
::testing::InitGoogleTest(&argc, argv);
STest::Random::seed();
return RUN_ALL_TESTS();
}
| cpp |
fprime | data/projects/fprime/Utils/Types/test/ut/CircularBuffer/CircularRules.hpp | /**
* CircularRules.hpp:
*
* This file specifies Rule classes for testing of the Types::CircularBuffer. These rules can then be used by the main
* testing program to test the code. These rules support rule-based random testing.
*
* Circular rules:
*
* 1. Serialize into CircularBuffer with sufficient space should work.
* 2. Serialize into CircularBuffer without sufficient space should error.
* 3. Peeking into CircularBuffer with data should work (all variants).
* 4. Peeking into CircularBuffer without data should error (all variants).
* 5. Rotations should increase space when there is enough data.
* 6. Rotations should error when there is not enough data.
* 7. A rule exists to help randomize items.
*
* @author mstarch
*/
#ifndef FPRIME_GROUNDINTERFACERULES_HPP
#define FPRIME_GROUNDINTERFACERULES_HPP
#include <FpConfig.hpp>
#include <Fw/Types/String.hpp>
#include <Utils/Types/test/ut/CircularBuffer/CircularState.hpp>
#include <STest/STest/Rule/Rule.hpp>
#include <STest/STest/Pick/Pick.hpp>
namespace Types {
/**
* SetupRandomBufferRule:
*
* This rule sets up a random buffer, and other random state.
*/
struct RandomizeRule : public STest::Rule<MockTypes::CircularState> {
// Constructor
RandomizeRule(const char *const name);
// Always valid
bool precondition(const MockTypes::CircularState& state);
// Will randomize the test state
void action(MockTypes::CircularState& truth);
};
/**
* SerializeOkRule:
*
* This rule tests that the circular buffer can accept data when it is valid for the buffer to accept data.
*/
struct SerializeOkRule : public STest::Rule<MockTypes::CircularState> {
// Constructor
SerializeOkRule(const char *const name);
// Valid precondition for when the buffer should accept data
bool precondition(const MockTypes::CircularState& state);
// Action that tests the buffer accepting data
void action(MockTypes::CircularState& state);
};
/**
* SerializeOverflowRule:
*
* This rule tests that the circular buffer cannot accept data when it is full.
*/
struct SerializeOverflowRule : public STest::Rule<MockTypes::CircularState> {
// Constructor
SerializeOverflowRule(const char *const name);
// Valid precondition for when the buffer should reject data
bool precondition(const MockTypes::CircularState& state);
// Action that tests the buffer overflowing with an error
void action(MockTypes::CircularState& state);
};
/**
* PeekOkRule:
*
* This rule tests that the circular buffer can peek correctly.
*/
struct PeekOkRule : public STest::Rule<MockTypes::CircularState> {
// Constructor
PeekOkRule(const char *const name);
// Peek ok available for when buffer size - remaining size <= peek size
bool precondition(const MockTypes::CircularState& state);
// Action that tests the buffer's ability to peek
void action(MockTypes::CircularState& state);
};
/**
* PeekOkRule:
*
* This rule tests that the circular buffer cannot peek when it should not peek.
*/
struct PeekBadRule : public STest::Rule<MockTypes::CircularState> {
// Constructor
PeekBadRule(const char *const name);
// Peek bad available for when buffer size - remaining size > peek size
bool precondition(const MockTypes::CircularState& state);
// Action that tests the buffer's ability to peek with a fail
void action(MockTypes::CircularState& state);
};
/**
* RotateOkRule:
*
* This rule tests that the circular buffer can rotate correctly.
*/
struct RotateOkRule : public STest::Rule<MockTypes::CircularState> {
// Constructor
RotateOkRule(const char *const name);
// Rotate is ok when there is more data then rotational size
bool precondition(const MockTypes::CircularState& state);
// Action that tests the buffer's ability to rotate
void action(MockTypes::CircularState& state);
};
/**
* RotateOkRule:
*
* This rule tests that the circular buffer cannot rotate when it should not rotate.
*/
struct RotateBadRule : public STest::Rule<MockTypes::CircularState> {
// Constructor
RotateBadRule(const char *const name);
// Rotate is bad when there is less data then rotational size
bool precondition(const MockTypes::CircularState& state);
// Action that tests the buffer's ability to rotate
void action(MockTypes::CircularState& state);
};
};
#endif //FPRIME_GROUNDINTERFACERULES_HPP
| hpp |
fprime | data/projects/fprime/Utils/Types/test/ut/CircularBuffer/CircularState.cpp | /**
* FakeLogger.cpp:
*
* Setup a fake logger for use with the testing. This allows for the capture of messages from the system and ensure that
* the proper log messages are coming through as expected.
*
* @author mstarch
*/
#include <STest/Pick/Pick.hpp>
#include <Utils/Types/test/ut/CircularBuffer/CircularState.hpp>
#include <cstdlib>
#include <cstring>
#include <gtest/gtest.h>
U8 CIRCULAR_BUFFER_MEMORY[MAX_BUFFER_SIZE];
namespace MockTypes {
CircularState::CircularState() :
m_remaining_size(static_cast<NATIVE_UINT_TYPE>(sizeof(CIRCULAR_BUFFER_MEMORY))),
m_random_size(MAX_BUFFER_SIZE),
m_peek_offset(0),
m_peek_type(0),
m_infinite_store(nullptr),
m_infinite_read(0),
m_infinite_write(0),
m_infinite_size(0),
m_test_buffer(CIRCULAR_BUFFER_MEMORY, static_cast<NATIVE_UINT_TYPE>(sizeof(CIRCULAR_BUFFER_MEMORY)))
{
memset(m_buffer, 0, sizeof m_buffer);
}
CircularState::~CircularState() {
if (m_infinite_size != 0) {
std::free(m_infinite_store);
}
}
// Generates a random buffer
NATIVE_UINT_TYPE CircularState::generateRandomBuffer() {
m_peek_offset = static_cast<NATIVE_UINT_TYPE>(STest::Pick::lowerUpper(0, sizeof(m_buffer)));
m_peek_type = static_cast<NATIVE_UINT_TYPE>(STest::Pick::lowerUpper(0, 4));
NATIVE_UINT_TYPE random_size = static_cast<NATIVE_UINT_TYPE>(STest::Pick::lowerUpper(0, sizeof(m_buffer)));
for (U32 i = 0; i < random_size; i++) {
m_buffer[i] = static_cast<U8>(STest::Pick::lowerUpper(0, 256));
}
this->m_random_size = random_size;
return random_size;
}
void CircularState::setRandom(NATIVE_UINT_TYPE random, NATIVE_UINT_TYPE peek_type, NATIVE_UINT_TYPE peek_offset) {
m_random_size = random;
m_peek_type = peek_type;
m_peek_offset = peek_offset;
}
NATIVE_UINT_TYPE CircularState::getPeekOffset() const {
return m_peek_offset;
}
NATIVE_UINT_TYPE CircularState::getPeekType() const {
return m_peek_type;
}
bool CircularState::addInfinite(const U8* buffer, NATIVE_UINT_TYPE size) {
// If we are out of "infinite space" add another MB, and check allocation
if ((m_infinite_write + size) > m_infinite_size) {
void* new_pointer = std::realloc(m_infinite_store, m_infinite_size + 1048576);
if (new_pointer == nullptr) {
return false;
}
m_infinite_store = static_cast<U8*>(new_pointer);
m_infinite_size += 1048576;
}
std::memcpy(m_infinite_store + m_infinite_write, buffer, size);
m_infinite_write += size;
return true;
}
bool CircularState::peek(U8*& buffer, NATIVE_UINT_TYPE size, NATIVE_UINT_TYPE offset) {
NATIVE_UINT_TYPE final_offset = m_infinite_read + offset;
if ((final_offset + size) > m_infinite_write) {
return false;
}
buffer = m_infinite_store + final_offset;
return true;
}
bool CircularState::rotate(NATIVE_UINT_TYPE size) {
// Fail if we try to rotate too far
if ((m_infinite_read + size) > m_infinite_write) {
return false;
}
m_infinite_read += size;
return true;
}
NATIVE_UINT_TYPE CircularState::getRandomSize() const {
return m_random_size;
}
const U8 *CircularState::getBuffer() const {
return m_buffer;
}
NATIVE_UINT_TYPE CircularState::getRemainingSize() const {
return m_remaining_size;
}
void CircularState::setRemainingSize(NATIVE_UINT_TYPE mRemainingSize) {
m_remaining_size = mRemainingSize;
}
Types::CircularBuffer& CircularState::getTestBuffer() {
return m_test_buffer;
}
void CircularState::checkSizes() const {
const NATIVE_UINT_TYPE allocated_size = (MAX_BUFFER_SIZE - m_remaining_size);
ASSERT_EQ(m_test_buffer.get_free_size(), m_remaining_size);
ASSERT_EQ(m_test_buffer.get_allocated_size(), allocated_size);
}
}
| cpp |
fprime | data/projects/fprime/Utils/Types/test/ut/CircularBuffer/CircularState.hpp | /**
* CircularState.hpp:
*
* Setup a fake logger for use with the testing. This allows for the capture of messages from the system and ensure that
* the proper log messages are coming through as expected.
*
* @author mstarch
*/
#include <FpConfig.hpp>
#include <Utils/Types/CircularBuffer.hpp>
#ifndef FPRIME_CIRCULARSTATE_HPP
#define FPRIME_CIRCULARSTATE_HPP
#define MAX_BUFFER_SIZE 10240
namespace MockTypes {
class CircularState {
public:
// Constructor
CircularState();
// Destructor
~CircularState();
/**
* Generates a random buffer for input to various calls to the CircularBuffer.
* @return size of this buffer
*/
NATIVE_UINT_TYPE generateRandomBuffer();
/**
* Sets the random settings
* @param random: random size
* @param peek_type: peek type (0-3)
* @param peek_offset: offset size
*/
void setRandom(NATIVE_UINT_TYPE random, NATIVE_UINT_TYPE peek_type, NATIVE_UINT_TYPE peek_offset);
/**
* Add to the infinite pool of data.
* @return true if successful, false otherwise
*/
bool addInfinite(const U8* buffer, NATIVE_UINT_TYPE size);
/**
* Grab a peek buffer for given size and offset.
* @return true if successful, false if cannot.
*/
bool peek(U8*& buffer, NATIVE_UINT_TYPE size, NATIVE_UINT_TYPE offset = 0);
/**
* Rotate the circular buffer.
* @param size: size to rotate
* @return true if successful, false otherwise
*/
bool rotate(NATIVE_UINT_TYPE size);
/**
* Get the size of the random buffer data.
* @return size of the buffer
*/
NATIVE_UINT_TYPE getRandomSize() const;
/**
* Get the size of the random buffer data.
* @return size of the buffer
*/
NATIVE_UINT_TYPE getPeekOffset() const;
/**
* Get the size of the random buffer data.
* @return size of the buffer
*/
NATIVE_UINT_TYPE getPeekType() const;
/**
* Gets a pointer to the random buffer.
* @return random buffer storing data
*/
const U8 *getBuffer() const;
/**
* Get the remaining size of the circular buffer. This is a shadow field.
* @return shadow field for circular buffer.
*/
NATIVE_UINT_TYPE getRemainingSize() const;
/**
* Set the remaining size shadow field input.
* @param mRemainingSize: remaining size shadow field
*/
void setRemainingSize(NATIVE_UINT_TYPE mRemainingSize);
/**
* Get the in-test circular buffer.
* @return in-test circular buffer
*/
Types::CircularBuffer& getTestBuffer();
/**
* Check allocated and free sizes
*/
void checkSizes() const;
private:
NATIVE_UINT_TYPE m_remaining_size;
NATIVE_UINT_TYPE m_random_size;
NATIVE_UINT_TYPE m_peek_offset;
NATIVE_UINT_TYPE m_peek_type;
U8 m_buffer[MAX_BUFFER_SIZE];
// May use just under 100MB of space
U8* m_infinite_store;
NATIVE_UINT_TYPE m_infinite_read;
NATIVE_UINT_TYPE m_infinite_write;
NATIVE_UINT_TYPE m_infinite_size;
Types::CircularBuffer m_test_buffer;
};
};
#endif //FPRIME_CIRCULARSTATE_HPP
| hpp |
fprime | data/projects/fprime/Utils/test/ut/RateLimiterTester.cpp | // ======================================================================
// \title RateLimiterTester.hpp
// \author vwong
// \brief cpp file for RateLimiter test harness implementation class
//
// \copyright
//
// Copyright (C) 2009-2020 California Institute of Technology.
//
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
// ======================================================================
#include "RateLimiterTester.hpp"
#include <ctime>
namespace Utils {
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
RateLimiterTester ::
RateLimiterTester()
{
}
RateLimiterTester ::
~RateLimiterTester()
{
}
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
void RateLimiterTester ::
testCounterTriggering()
{
U32 testCycles[] = {0, 5, 50, 832};
for (U32 i = 0; i < FW_NUM_ARRAY_ELEMENTS(testCycles); i++) {
const U32 cycles = testCycles[i];
// triggers at the beginning
RateLimiter limiter(cycles, 0);
ASSERT_TRUE(limiter.trigger());
limiter.reset();
// does not trigger if skipped
if (cycles > 0) {
limiter.setCounter(1);
ASSERT_FALSE(limiter.trigger());
limiter.reset();
}
// test number of times triggered
const U32 numIter = 10000;
U32 triggerCount = 0;
for (U32 iter = 0; iter < numIter; iter++) {
bool shouldTrigger = (cycles == 0) || (iter % cycles == 0);
bool triggered = limiter.trigger();
ASSERT_EQ(shouldTrigger, triggered) << " for cycles " << cycles << " at " << iter;
triggerCount += triggered;
}
if (cycles > 0) {
U32 expectedCount = (numIter / cycles) + (numIter % cycles > 0);
ASSERT_EQ(triggerCount, expectedCount);
}
}
}
void RateLimiterTester ::
testTimeTriggering()
{
U32 testCycles[] = {0, 5, 50, 832};
for (U32 i = 0; i < FW_NUM_ARRAY_ELEMENTS(testCycles); i++) {
const U32 cycles = testCycles[i];
Fw::Time timeCyclesTime(cycles, 0);
// triggers at the beginning
RateLimiter limiter(0, cycles);
ASSERT_TRUE(limiter.trigger(Fw::Time::zero()));
limiter.reset();
// does not trigger if skipped
if (cycles > 0) {
limiter.setTime(Fw::Time(1,0));
ASSERT_FALSE(limiter.trigger(Fw::Time::zero()));
limiter.reset();
}
// test number of times triggered
const U32 numIter = 100000;
Fw::Time curTime(0, 0);
Fw::Time nextTriggerTime(0, 0);
srand(0x30931842);
for (U32 iter = 0; iter < numIter; iter++) {
curTime.add(0, (rand() % 5 + 1) * 100000);
bool shouldTrigger = (cycles == 0) || (curTime >= nextTriggerTime);
bool triggered = limiter.trigger(curTime);
ASSERT_EQ(shouldTrigger, triggered) << " for cycles " << cycles << " at " << curTime.getSeconds() << "." << curTime.getUSeconds();
if (triggered) {
nextTriggerTime = Fw::Time::add(curTime, timeCyclesTime);
}
}
}
}
void RateLimiterTester ::
testCounterAndTimeTriggering()
{
RateLimiter limiter;
U32 testCounterCycles[] = {37, 981, 4110};
U32 testTimeCycles[] = {12, 294, 1250};
for (U32 i = 0; i < (FW_NUM_ARRAY_ELEMENTS(testCounterCycles) * FW_NUM_ARRAY_ELEMENTS(testTimeCycles)); i++) {
const U32 counterCycles = testCounterCycles[i % FW_NUM_ARRAY_ELEMENTS(testCounterCycles)];
const U32 timeCycles = testTimeCycles[i / FW_NUM_ARRAY_ELEMENTS(testCounterCycles)];
Fw::Time timeCyclesTime(timeCycles, 0);
limiter.setCounterCycle(counterCycles);
limiter.setTimeCycle(timeCycles);
limiter.reset();
// triggers at the beginning
RateLimiter limiter(counterCycles, timeCycles);
ASSERT_TRUE(limiter.trigger(Fw::Time::zero()));
limiter.reset();
// test trigger locations
const U32 numIter = 100000; // each iter is 0.1 seconds
Fw::Time curTime(0, 0);
U32 lastTriggerIter = 0;
Fw::Time nextTriggerTime(0, 0);
srand(0x28E1ACC2);
for (U32 iter = 0; iter < numIter; iter++) {
curTime.add(0, (rand() % 5 + 1) * 100000);
bool shouldTrigger = ((iter-lastTriggerIter) % counterCycles == 0) || (curTime >= nextTriggerTime);
bool triggered = limiter.trigger(curTime);
ASSERT_EQ(shouldTrigger, triggered) << " for cycles " << counterCycles << "/" << timeCycles << " at " << iter << "/" << curTime.getSeconds() << "." << curTime.getUSeconds();
if (triggered) {
nextTriggerTime = Fw::Time::add(curTime, timeCyclesTime);
lastTriggerIter = iter;
}
}
}
}
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
void RateLimiterTester ::
initComponents()
{
}
} // end namespace Utils
| cpp |
fprime | data/projects/fprime/Utils/test/ut/main.cpp | // ----------------------------------------------------------------------
// Main.cpp
// ----------------------------------------------------------------------
#include "LockGuardTester.hpp"
#include "RateLimiterTester.hpp"
#include "TokenBucketTester.hpp"
TEST(LockGuardTest, TestLocking) {
Utils::LockGuardTester tester;
tester.testLocking();
}
TEST(RateLimiterTest, TestCounterTriggering) {
Utils::RateLimiterTester tester;
tester.testCounterTriggering();
}
TEST(RateLimiterTest, TestTimeTriggering) {
Utils::RateLimiterTester tester;
tester.testTimeTriggering();
}
TEST(RateLimiterTest, TestCounterAndTimeTriggering) {
Utils::RateLimiterTester tester;
tester.testCounterAndTimeTriggering();
}
TEST(TokenBucketTest, TestTriggering) {
Utils::TokenBucketTester tester;
tester.testTriggering();
}
TEST(TokenBucketTest, TestReconfiguring) {
Utils::TokenBucketTester tester;
tester.testReconfiguring();
}
TEST(TokenBucketTest, TestInitialSettings) {
Utils::TokenBucketTester tester;
tester.testInitialSettings();
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| cpp |
fprime | data/projects/fprime/Utils/test/ut/LockGuardTester.cpp | // ======================================================================
// \title LockGuardTester.hpp
// \author vwong
// \brief cpp file for LockGuard test harness implementation class
//
// \copyright
//
// Copyright (C) 2009-2020 California Institute of Technology.
//
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
// ======================================================================
#include "LockGuardTester.hpp"
#include <ctime>
#include <Os/Task.hpp>
namespace Utils {
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
LockGuardTester ::
LockGuardTester()
{
}
LockGuardTester ::
~LockGuardTester()
{
}
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
struct TaskData {
Os::Mutex mutex;
int i;
};
void taskMethod(void* ptr)
{
TaskData* data = static_cast<TaskData*>(ptr);
LockGuard guard(data->mutex);
data->i++;
}
void LockGuardTester ::
testLocking()
{
TaskData data;
data.i = 0;
Os::Task testTask;
Os::Task::TaskStatus stat;
Os::TaskString name("TestTask");
{
LockGuard guard(data.mutex);
stat = testTask.start(name, taskMethod, &data);
ASSERT_EQ(stat, Os::Task::TASK_OK);
Os::Task::delay(100);
ASSERT_EQ(data.i, 0);
}
Os::Task::delay(100);
{
LockGuard guard(data.mutex);
ASSERT_EQ(data.i, 1);
}
stat = testTask.join(nullptr);
ASSERT_EQ(stat, Os::Task::TASK_OK);
}
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
void LockGuardTester ::
initComponents()
{
}
} // end namespace Utils
| cpp |
fprime | data/projects/fprime/Utils/test/ut/TokenBucketTester.hpp | // ======================================================================
// \title Util/test/ut/TokenBucketTester.hpp
// \author vwong
// \brief hpp file for TokenBucket test harness implementation class
//
// \copyright
//
// Copyright (C) 2009-2020 California Institute of Technology.
//
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
// ======================================================================
#ifndef TOKENBUCKETTESTER_HPP
#define TOKENBUCKETTESTER_HPP
#include "Utils/TokenBucket.hpp"
#include <FpConfig.hpp>
#include "gtest/gtest.h"
namespace Utils {
class TokenBucketTester
{
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
public:
//! Construct object TokenBucketTester
//!
TokenBucketTester();
//! Destroy object TokenBucketTester
//!
~TokenBucketTester();
public:
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
void testTriggering();
void testReconfiguring();
void testInitialSettings();
private:
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
//! Initialize components
//!
void initComponents();
private:
// ----------------------------------------------------------------------
// Variables
// ----------------------------------------------------------------------
};
} // end namespace Utils
#endif
| hpp |
fprime | data/projects/fprime/Utils/test/ut/TokenBucketTester.cpp | // ======================================================================
// \title TokenBucketTester.hpp
// \author vwong
// \brief cpp file for TokenBucket test harness implementation class
//
// \copyright
//
// Copyright (C) 2009-2020 California Institute of Technology.
//
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
// ======================================================================
#include "TokenBucketTester.hpp"
#include <ctime>
namespace Utils {
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
TokenBucketTester ::
TokenBucketTester()
{
}
TokenBucketTester ::
~TokenBucketTester()
{
}
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
void TokenBucketTester ::
testTriggering()
{
const U32 interval = 1000000;
U32 testMaxTokens[] = {1, 5, 50, 832};
for (U32 i = 0; i < FW_NUM_ARRAY_ELEMENTS(testMaxTokens); i++) {
const U32 maxTokens = testMaxTokens[i];
TokenBucket bucket(interval, maxTokens);
// can activate maxTokens times in a row
for (U32 j = 0; j < maxTokens; j++) {
bool triggered = bucket.trigger(Fw::Time(0, 0));
ASSERT_TRUE(triggered);
ASSERT_EQ(bucket.getTokens(), maxTokens - j - 1);
}
// replenish
bucket.replenish();
Fw::Time time(0, 0);
const U32 attempts = maxTokens * 5;
Fw::Time attemptInterval(0, interval / 4);
U32 triggerCount = 0;
for (U32 attempt = 0; attempt < attempts; attempt++) {
triggerCount += bucket.trigger(time);
time = Fw::Time::add(time, attemptInterval);
}
U32 expected = maxTokens + (attempts - 1) / 4;
ASSERT_EQ(expected, triggerCount);
}
}
void TokenBucketTester ::
testReconfiguring()
{
U32 initialInterval = 1000000;
U32 initialMaxTokens = 5;
TokenBucket bucket(initialInterval, initialMaxTokens);
ASSERT_EQ(bucket.getReplenishInterval(), initialInterval);
ASSERT_EQ(bucket.getMaxTokens(), initialMaxTokens);
ASSERT_EQ(bucket.getTokens(), initialMaxTokens);
// trigger
bucket.trigger(Fw::Time(0, 0));
ASSERT_EQ(bucket.getTokens(), initialMaxTokens-1);
// replenished, then triggered
bucket.trigger(Fw::Time(1, 0));
ASSERT_EQ(bucket.getTokens(), initialMaxTokens-1);
// set new interval, can't replenish using old interval
U32 newInterval = 2000000;
bucket.setReplenishInterval(newInterval);
ASSERT_EQ(bucket.getReplenishInterval(), newInterval);
ASSERT_TRUE(bucket.trigger(Fw::Time(2, 0)));
ASSERT_EQ(bucket.getTokens(), initialMaxTokens-2);
// set new max tokens, replenish up to new max
U32 newMaxTokens = 10;
bucket.setMaxTokens(newMaxTokens);
ASSERT_EQ(bucket.getMaxTokens(), newMaxTokens);
ASSERT_TRUE(bucket.trigger(Fw::Time(20, 0)));
ASSERT_EQ(bucket.getTokens(), newMaxTokens-1);
// set new rate, replenish quickly
while (bucket.trigger(Fw::Time(0,0)));
bucket.setReplenishInterval(1000000);
U32 newRate = 2;
bucket.setReplenishRate(newRate);
ASSERT_EQ(bucket.getReplenishRate(), newRate);
ASSERT_TRUE(bucket.trigger(Fw::Time(21, 0)));
ASSERT_EQ(bucket.getTokens(), 1);
}
void TokenBucketTester ::
testInitialSettings()
{
U32 interval = 1000000;
U32 maxTokens = 5;
U32 rate = 2;
U32 startTokens = 2;
Fw::Time startTime(5,0);
TokenBucket bucket(interval, maxTokens, rate, startTokens, startTime);
ASSERT_NE(bucket.getTokens(), maxTokens);
ASSERT_EQ(bucket.getTokens(), startTokens);
ASSERT_EQ(bucket.getReplenishRate(), rate);
for (U32 i = 0; i < startTokens; i++) {
bool triggered = bucket.trigger(Fw::Time(0,0));
ASSERT_TRUE(triggered);
}
ASSERT_FALSE(bucket.trigger(Fw::Time(0,0)));
}
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
void TokenBucketTester ::
initComponents()
{
}
} // end namespace Utils
| cpp |
fprime | data/projects/fprime/Utils/test/ut/RateLimiterTester.hpp | // ======================================================================
// \title Util/test/ut/RateLimiterTester.hpp
// \author vwong
// \brief hpp file for RateLimiter test harness implementation class
//
// \copyright
//
// Copyright (C) 2009-2020 California Institute of Technology.
//
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
// ======================================================================
#ifndef RATELIMITERTESTER_HPP
#define RATELIMITERTESTER_HPP
#include "Utils/RateLimiter.hpp"
#include <FpConfig.hpp>
#include "gtest/gtest.h"
namespace Utils {
class RateLimiterTester
{
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
public:
//! Construct object RateLimiterTester
//!
RateLimiterTester();
//! Destroy object RateLimiterTester
//!
~RateLimiterTester();
public:
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
void testCounterTriggering();
void testTimeTriggering();
void testCounterAndTimeTriggering();
private:
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
//! Initialize components
//!
void initComponents();
private:
// ----------------------------------------------------------------------
// Variables
// ----------------------------------------------------------------------
};
} // end namespace Utils
#endif
| hpp |
fprime | data/projects/fprime/Utils/test/ut/LockGuardTester.hpp | // ======================================================================
// \title Util/test/ut/LockGuardTester.hpp
// \author vwong
// \brief hpp file for LockGuard test harness implementation class
//
// \copyright
//
// Copyright (C) 2009-2020 California Institute of Technology.
//
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
// ======================================================================
#ifndef LOCKGUARDTESTER_HPP
#define LOCKGUARDTESTER_HPP
#include "Utils/LockGuard.hpp"
#include <FpConfig.hpp>
#include "gtest/gtest.h"
namespace Utils {
class LockGuardTester
{
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
public:
//! Construct object LockGuardTester
//!
LockGuardTester();
//! Destroy object LockGuardTester
//!
~LockGuardTester();
public:
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
void testLocking();
private:
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
//! Initialize components
//!
void initComponents();
private:
// ----------------------------------------------------------------------
// Variables
// ----------------------------------------------------------------------
};
} // end namespace Utils
#endif
| hpp |
fprime | data/projects/fprime/STest/STest/testing.hpp | // ======================================================================
// \title testing.hpp
// \author Rob Bocchino
// \brief Symbols for testing
//
// \copyright
// Copyright (C) 2018 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
// ======================================================================
#ifndef STEST_TESTING_HPP
#define STEST_TESTING_HPP
#include "include/gtest/gtest.h"
#endif
| hpp |
fprime | data/projects/fprime/STest/STest/Scenario/InterleavedScenario.hpp | // ======================================================================
// \title InterleavedScenario.hpp
// \author bocchino
// \brief Randomly interleave several scenarios
//
// \copyright
// Copyright (C) 2017 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
// ======================================================================
#ifndef STest_InterleavedScenario_HPP
#define STest_InterleavedScenario_HPP
#include <cassert>
#include <cstring>
#include "STest/Scenario/Scenario.hpp"
#include "STest/Scenario/ScenarioArray.hpp"
namespace STest {
//! Randomly interleave several scenarios
template<typename State> class InterleavedScenario :
public Scenario<State>
{
public:
// ----------------------------------------------------------------------
// Constructors and destructors
// ----------------------------------------------------------------------
//! Construct an InterleavedScenario object
InterleavedScenario(
const char *const name, //!< The name of the scenario
Scenario<State>** scenarios, //!< An array containing the scenarios to interleave
const U32 size //!< The size of the array
) :
Scenario<State>(name),
scenarioArray(new ScenarioArray<State>(scenarios, size)),
seen(new bool[size])
{
}
//! Destroy an InterleavedScenario object
~InterleavedScenario() {
if (this->scenarioArray != nullptr) {
delete this->scenarioArray;
}
if (this->seen != nullptr) {
delete[] this->seen;
}
}
protected:
// ----------------------------------------------------------------------
// Scenario implementation
// ----------------------------------------------------------------------
//! The virtual implementation of reset required by Scenario
void reset_Scenario() {
assert(this->scenarioArray != nullptr);
this->scenarioArray->reset();
}
//! The virtual implementation of nextRule required by Scenario
//! \return The next rule, assuming isDone() is false, or nullptr if none
Rule<State>* nextRule_Scenario(
State& state //!< The system state
) {
assert(this->scenarioArray != nullptr);
Rule<State>* rule = nullptr;
memset(this->seen, 0, this->scenarioArray->size * sizeof(bool));
U32 numSeen = 0;
Scenario<State>* *const scenarios =
this->scenarioArray->getScenarios();
U32 numIterations = 0;
const U32 maxIterations = 0xFFFFFFFFU;
while (numSeen < this->scenarioArray->size) {
assert(numIterations < maxIterations);
++numIterations;
const U32 i = this->scenarioArray->getRandomIndex();
if (this->seen[i]) {
continue;
}
rule = scenarios[i]->nextRule(state);
if (rule != nullptr) {
break;
}
this->seen[i] = true;
++numSeen;
}
return rule;
}
//! The virtual implementation of isDone required by Scenario
//! \return Whether the scenario is done
bool isDone_Scenario() const {
bool result = true;
Scenario<State>* *const scenarios =
this->scenarioArray->getScenarios();
assert(scenarios != nullptr);
for (U32 i = 0; i < scenarioArray->size; ++i) {
assert(scenarios[i] != nullptr);
if (!scenarios[i]->isDone()) {
result = false;
break;
}
}
return result;
}
protected:
// ----------------------------------------------------------------------
// Protected member variables
// ----------------------------------------------------------------------
//! The scenarios to interleave
ScenarioArray<State>* scenarioArray;
//! An array to store the scenarios seen
bool* seen;
};
}
#endif
| hpp |
fprime | data/projects/fprime/STest/STest/Scenario/ConditionalIteratedScenario.hpp | // ======================================================================
// \title ConditionalIteratedScenario.hpp
// \author bocchino
// \brief Iterate a scenario while a condition holds
//
// \copyright
// Copyright (C) 2017 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
// ======================================================================
#ifndef STest_ConditionalIteratedScenario_HPP
#define STest_ConditionalIteratedScenario_HPP
#include "STest/Scenario/IteratedScenario.hpp"
namespace STest {
//! Iterate a scenario while a condition holds
template<typename State> class ConditionalIteratedScenario :
public IteratedScenario<State>
{
public:
// ----------------------------------------------------------------------
// Constructors and destructors
// ----------------------------------------------------------------------
//! Construct a ConditionalIteratedScenario
ConditionalIteratedScenario(
const char *const name, //!< The name of the ConditionalIteratedScenario
IteratedScenario<State>& scenario //!< The scenario to run
) :
IteratedScenario<State>(name),
scenario(scenario),
done(false)
{
}
//! Destroy object ConditionalIteratedScenario
virtual ~ConditionalIteratedScenario() {
}
protected:
// ----------------------------------------------------------------------
// IteratedScenario implementation
// ----------------------------------------------------------------------
//! The virtual implementation of reset required by IteratedScenario
void reset_IteratedScenario() {
this->scenario.reset();
this->done = this->scenario.isDone();
}
//! The virtual implementation of nextScenario required by IteratedScenario
//! \return The next scenario, assuming isDone() is false, or nullptr if none
Scenario<State>* nextScenario_IteratedScenario(
State& state //!< The system state
) {
Scenario<State>* scenario = nullptr;
if (!this->condition_ConditionalIteratedScenario(state)) {
this->done = true;
}
if (!this->isDone()) {
scenario = this->scenario.nextScenario(state);
this->done = this->scenario.isDone();
}
this->nextScenario_ConditionalIteratedScenario(scenario);
return scenario;
}
//! The virtual implementation of isDone required by IteratedScenario
//! \return Whether the scenario is done
bool isDone_IteratedScenario() const {
return this->done;
}
protected:
// ----------------------------------------------------------------------
// Protected virtual methods
// ----------------------------------------------------------------------
//! The virtual condition required by ConditionalIteratedScenario
//! \return Whether the condition holds
virtual bool condition_ConditionalIteratedScenario(
const State& state //!< The system state
) const = 0;
//! The virtual implementation of nextScenario required by ConditionalIteratedScenario
virtual void nextScenario_ConditionalIteratedScenario(
const Scenario<State> *const nextScenario //!< The scenario being returned
) = 0;
protected:
// ----------------------------------------------------------------------
// Protected member variables
// ----------------------------------------------------------------------
//! The scenario to run
IteratedScenario<State>& scenario;
//! Whether the iterated scenario is done
bool done;
};
}
#endif
| hpp |
fprime | data/projects/fprime/STest/STest/Scenario/ScenarioArray.hpp | // ======================================================================
// \title ScenarioArray.hpp
// \author bocchino
// \brief An array of scenarios
//
// \copyright
// Copyright (C) 2017 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
// ======================================================================
#ifndef STest_ScenarioArray_HPP
#define STest_ScenarioArray_HPP
#include <cassert>
#include "STest/Random/Random.hpp"
namespace STest {
//! An array of scenarios
template<typename State>class ScenarioArray {
public:
// ----------------------------------------------------------------------
// Constructors and destructors
// ----------------------------------------------------------------------
//! Construct a ScenarioArray object
ScenarioArray (
Scenario<State>** scenarios, //!< The scenarios in the array
const U32 size //!< The number of scenarios in the array
) :
size(size),
scenarios(scenarios),
sequenceIndex(0)
{
}
public:
// ----------------------------------------------------------------------
// Public instance methods
// ----------------------------------------------------------------------
//! Get a random index into the array
//! \return The index
U32 getRandomIndex() const {
const U32 index = Random::startLength(0, this->size);
assert(index < this->size);
return index;
}
//! Reset the sequence index and reset all child scenarios
void reset() {
this->sequenceIndex = 0;
for (U32 i = 0; i < this->size; ++i) {
this->scenarios[i]->reset();
}
}
//! Return the next scenario in the sequence
Scenario<State>* nextScenario() {
Scenario<State>* scenario = nullptr;
if (this->sequenceIndex < this->size) {
scenario = this->scenarios[this->sequenceIndex];
++this->sequenceIndex;
}
if (scenario != nullptr) {
scenario->reset();
}
return scenario;
}
//! Get the scenarios
Scenario<State>** getScenarios() const {
assert(this->scenarios != nullptr);
return this->scenarios;
}
public:
// ----------------------------------------------------------------------
// Public member variables
// ----------------------------------------------------------------------
//! The number of scenarios in the array
const U32 size;
private:
// ----------------------------------------------------------------------
// Private member variables
// ----------------------------------------------------------------------
//! The scenarios in the array
Scenario<State>** scenarios;
//! The sequence index
U32 sequenceIndex;
};
}
#endif
| hpp |
fprime | data/projects/fprime/STest/STest/Scenario/RepeatedRuleScenario.hpp | // ======================================================================
// \title RepeatedRuleScenario.hpp
// \author bocchino
// \brief Repeatedly apply a rule
//
// \copyright
// Copyright (C) 2017 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
// ======================================================================
#ifndef STest_RepeatedRuleScenario_HPP
#define STest_RepeatedRuleScenario_HPP
#include "STest/Scenario/Scenario.hpp"
namespace STest {
//! Repeatedly apply a rule
template<typename State> class RepeatedRuleScenario :
public Scenario<State>
{
public:
// ----------------------------------------------------------------------
// Constructors and destructors
// ----------------------------------------------------------------------
//! Construct object RepeatedRuleScenario
RepeatedRuleScenario(
Rule<State>& rule //!< The rule
) :
Scenario<State>(rule.getName()),
rule(rule)
{
}
public:
// ----------------------------------------------------------------------
// Scenario implementation
// ----------------------------------------------------------------------
//! The virtual implementation of reset required by Scenario
void reset_Scenario() {
// Do nothing
}
//! The virtual implementation of nextRule required by Scenario
//! \return The next rule, assuming isDone() is false, or nullptr if none
Rule<State>* nextRule_Scenario(
State& state //!< The system state
) {
Rule<State> *rule = nullptr;
if (this->rule.precondition(state)) {
rule = &this->rule;
}
return rule;
}
//! The virtual implementation of isDone required by Scenario
//! \return Whether the scenario is done
bool isDone_Scenario() const {
return false;
}
private:
// ----------------------------------------------------------------------
// Private member variables
// ----------------------------------------------------------------------
//! The rule
Rule<State>& rule;
};
}
#endif
| hpp |
fprime | data/projects/fprime/STest/STest/Scenario/RuleScenario.hpp | // ======================================================================
// \title RuleScenario.hpp
// \author bocchino
// \brief Apply a single rule once
//
// \copyright
// Copyright (C) 2017 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
// ======================================================================
#ifndef STest_RuleScenario_HPP
#define STest_RuleScenario_HPP
#include "STest/Scenario/Scenario.hpp"
namespace STest {
//! Apply a single rule once
template<typename State> class RuleScenario :
public Scenario<State>
{
public:
// ----------------------------------------------------------------------
// Constructors and destructors
// ----------------------------------------------------------------------
//! Construct object RuleScenario
RuleScenario(
Rule<State>& rule //!< The rule
) :
Scenario<State>(rule.name),
rule(rule),
done(false)
{
}
public:
// ----------------------------------------------------------------------
// Scenario implementation
// ----------------------------------------------------------------------
//! The virtual implementation of reset required by Scenario
void reset_Scenario() {
this->done = false;
}
//! the virtual implementation of nextRule required by Scenario
//! \return The next rule, assuming isDone() is false, or nullptr if none
Rule<State>* nextRule_Scenario(
State& state //!< The system state
) {
Rule<State> *rule = nullptr;
if (!this->isDone() && this->rule.precondition(state)) {
rule = &this->rule;
this->done = true;
}
return rule;
}
//! The virtual implementation of isDone required by Scenario
//! \return Whether the scenario is done
bool isDone_Scenario() const {
return this->done;
}
private:
// ----------------------------------------------------------------------
// Private member variables
// ----------------------------------------------------------------------
//! The rule
Rule<State>& rule;
//! Whether the scenario is done
bool done;
};
}
#endif
| hpp |
fprime | data/projects/fprime/STest/STest/Scenario/Scenario.hpp | // ======================================================================
// \title Scenario.hpp
// \author bocchino
// \brief A test scenario
//
// \copyright
// Copyright (C) 2017 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
// ======================================================================
#ifndef STest_Scenario_HPP
#define STest_Scenario_HPP
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include "STest/Random/Random.hpp"
#include "STest/Rule/Rule.hpp"
namespace STest {
//! A test scenario
template<typename State> class Scenario {
public:
// ----------------------------------------------------------------------
// Constructors and destructors
// ----------------------------------------------------------------------
//! Construct a Scenario object
Scenario(
const char *const name //!< The name of the scenario
) :
name(name),
showRules(false)
{
this->setShowRules();
}
//! Destroy a Scenario object
virtual ~Scenario() {
}
public:
// ----------------------------------------------------------------------
// Public instance methods
// ----------------------------------------------------------------------
//! Reset the scenario state
void reset() {
this->reset_Scenario();
}
//! Run the scenario until there are no more rules to apply
//! \return The number of steps taken
U32 run(
State& state //!< The system state
) {
U32 numSteps = 0;
this->runHelper(state, numSteps);
return numSteps;
}
//! Return the next rule to apply
//! \return The next rule, or nullptr if none
Rule<State>* nextRule(
State& state //!< The system state
) {
Rule<State> *rule = nullptr;
if (!this->isDone()) {
rule = this->nextRule_Scenario(state);
}
return rule;
}
//! Query whether the scenario is done
//! \return Whether the scenario is done
bool isDone() const {
return this->isDone_Scenario();
}
protected:
// ----------------------------------------------------------------------
// Protected virtual methods
// ----------------------------------------------------------------------
//! The virtual implementation of reset required by Scenario
virtual void reset_Scenario() = 0;
//! The virtual implementation of nextRule required by Scenario
//! \return The next rule, assuming isDone() is false, or nullptr if none
virtual Rule<State>* nextRule_Scenario(
State& state //!< The system state
) = 0;
//! The virtual implementation of isDone required by Scenario
//! \return Whether the scenario is done
virtual bool isDone_Scenario() const = 0;
private:
// ----------------------------------------------------------------------
// Private helper functions
// ----------------------------------------------------------------------
//! Run helper function
void runHelper(
State& state, //!< The system state
U32& numSteps //!< The number of steps
) {
this->reset();
Rule<State>* rule = this->nextRule(state);
while (rule != nullptr) {
this->applyNextRule(*rule, state);
++numSteps;
if (this->isDone()) {
break;
}
rule = this->nextRule(state);
}
}
//! Apply the next rule
//! \return The number of steps taken
void applyNextRule(
Rule<State>& rule, //!< The rule
State& state //!< The state
) {
if (this->showRules) {
printf(
"[Scenario %s] Applying rule %s\n",
this->name,
rule.getName()
);
}
rule.apply(state);
}
//! Set showRules
void setShowRules() {
const int status = system("test -f show-rules");
if (status == 0) {
showRules = true;
}
}
public:
// ----------------------------------------------------------------------
// Public member variables
// ----------------------------------------------------------------------
//! The name of the scenario
const char *const name;
private:
// ----------------------------------------------------------------------
// Private member variables
// ----------------------------------------------------------------------
//! Whether to report rule applications
bool showRules;
};
}
#endif
| hpp |
fprime | data/projects/fprime/STest/STest/Scenario/SequenceScenario.hpp | // ======================================================================
// \title SequenceScenario.hpp
// \author bocchino
// \brief A sequence of scenarios
//
// \copyright
// Copyright (C) 2017 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
// ======================================================================
#ifndef STest_SequenceScenario_HPP
#define STest_SequenceScenario_HPP
#include <cassert>
#include "STest/Scenario/IteratedScenario.hpp"
#include "STest/Scenario/ScenarioArray.hpp"
namespace STest {
//! A sequence of scenarios
template<typename State> class SequenceScenario :
public IteratedScenario<State>
{
public:
// ----------------------------------------------------------------------
// Constructors and destructors
// ----------------------------------------------------------------------
//! Construct a SequenceScenario from an array of scenarios
SequenceScenario(
const char *const name, //!< The name of the scenario
Scenario<State>** scenarios, //!< The scenarios in the array
const U32 size //!< The size of the array
) :
IteratedScenario<State>(name),
scenarioArray(new ScenarioArray<State>(scenarios, size)),
done(false)
{
}
//! Destroy object SequenceScenario
virtual ~SequenceScenario() {
delete this->scenarioArray;
}
protected:
// ----------------------------------------------------------------------
// IteratedScenario implementation
// ----------------------------------------------------------------------
//! The virtual implementation of reset required by IteratedScenario
void reset_IteratedScenario() {
this->scenarioArray->reset();
this->done = false;
}
//! The virtual implementation of nextScenario required by IteratedScenario
//! \return The next scenario, assuming isDone() is false, or nullptr if none
Scenario<State>* nextScenario_IteratedScenario(
State& state //!< The system state
) {
Scenario<State> *scenario = nullptr;
if (!this->done) {
assert(this->scenarioArray != nullptr);
scenario = this->scenarioArray->nextScenario();
}
if (!this->done and scenario == nullptr) {
this->done = true;
}
return scenario;
}
//! The virtual implementation of isDone required by IteratedScenario
//! \return Whether the scenario is done
bool isDone_IteratedScenario() const {
return this->done;
}
protected:
// ----------------------------------------------------------------------
// Protected member variables
// ----------------------------------------------------------------------
//! The scenario array
ScenarioArray<State>* scenarioArray;
//! Whether the sequence scenario is done
bool done;
};
}
#endif
| hpp |
fprime | data/projects/fprime/STest/STest/Scenario/RandomlyBoundedScenario.hpp | // ======================================================================
// \title RandomlyBoundedScenario.hpp
// \author bocchino
// \brief Run a scenario, applying a random bound on the number of steps
//
// \copyright
// Copyright (C) 2017 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
// ======================================================================
#ifndef STest_RandomlyBoundedScenario_HPP
#define STest_RandomlyBoundedScenario_HPP
#include "STest/Random/Random.hpp"
#include "STest/Scenario/BoundedScenario.hpp"
namespace STest {
//! Run a scenario, applying a random bound on the number of steps
template<typename State> class RandomlyBoundedScenario :
public Scenario<State>
{
public:
// ----------------------------------------------------------------------
// Constructors and destructors
// ----------------------------------------------------------------------
//! Construct a RandomlyBoundedScenario
RandomlyBoundedScenario(
const char *const name, //!< The name of the bounded scenario
Scenario<State>& scenario, //!< The scenario to run
const U32 start, //!< The start value of the random range
const U32 length //!< The number of values in the random range, including the start value
) :
Scenario<State>(name),
scenario(scenario),
start(start),
length(length),
boundedScenario(nullptr)
{
}
//! Destroy object RandomlyBoundedScenario
virtual ~RandomlyBoundedScenario() {
if (this->boundedScenario != nullptr) {
delete this->boundedScenario;
}
}
private:
// ----------------------------------------------------------------------
// Scenario implementation
// ----------------------------------------------------------------------
//! The virtual implementation of reset required by Scenario
void reset_Scenario() {
if (this->boundedScenario != nullptr) {
delete this->boundedScenario;
}
const U32 bound = Random::startLength(this->start, this->length);
this->boundedScenario = new BoundedScenario<State>(
this->name,
this->scenario,
bound
);
assert(this->boundedScenario != nullptr);
this->boundedScenario->reset();
}
//! The virtual implementation of nextRule required by Scenario
//! \return The next rule, assuming isDone() is false, or nullptr if none
Rule<State>* nextRule_Scenario(
State& state //!< The system state
) {
assert(this->boundedScenario != nullptr);
return this->boundedScenario->nextRule(state);
}
//! The virtual implementation of isDone required by Scenario
//! \return Whether the scenario is done
bool isDone_Scenario() const {
assert(this->boundedScenario != nullptr);
return this->boundedScenario->isDone();
}
private:
// ----------------------------------------------------------------------
// Private member variables
// ----------------------------------------------------------------------
//! The scenario to run
Scenario<State>& scenario;
//! The start value of the random range
const U32 start;
//! The number of values in the random range, including the start value
const U32 length;
//! The underlying bounded scenario
BoundedScenario<State>* boundedScenario;
};
}
#endif
| hpp |
fprime | data/projects/fprime/STest/STest/Scenario/BoundedScenario.hpp | // ======================================================================
// \title BoundedScenario.hpp
// \author bocchino
// \brief Run a scenario, bounding the number of steps
//
// \copyright
// Copyright (C) 2017 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
// ======================================================================
#ifndef STest_BoundedScenario_HPP
#define STest_BoundedScenario_HPP
#include "STest/Scenario/ConditionalScenario.hpp"
namespace STest {
//! Run a scenario, bounding the number of steps
template<typename State> class BoundedScenario :
public ConditionalScenario<State>
{
public:
// ----------------------------------------------------------------------
// Constructors and destructors
// ----------------------------------------------------------------------
//! Construct a BoundedScenario object
BoundedScenario(
const char *const name, //!< The name of the bounded scenario
Scenario<State>& scenario, //!< The scenario to run
const U32 bound //!< The bound
) :
ConditionalScenario<State>(name, scenario),
numSteps(0),
bound(bound)
{
}
//! Destroy a BoundedScenario object
~BoundedScenario() {
}
public:
// ----------------------------------------------------------------------
// ConditionalScenario implementation
// ----------------------------------------------------------------------
//! The virtual condition required by ConditionalScenario
//! \return Whether the condition holds
bool condition_ConditionalScenario(
const State& state //!< The system state
) const {
return this->numSteps < this->bound;
}
//! The virtual implementation of nextRule required by ConditionalScenario
void nextRule_ConditionalScenario(
const Rule<State> *const nextRule //!< The next rule
) {
if (nextRule != nullptr) {
++this->numSteps;
}
}
//! The virtual implementation of reset required by ConditionalScenario
void reset_ConditionalScenario() {
this->numSteps = 0;
}
private:
// ----------------------------------------------------------------------
// Private member variables
// ----------------------------------------------------------------------
//! The number of steps
U32 numSteps;
//! The bound on the number of steps
const U32 bound;
};
}
#endif
| hpp |
fprime | data/projects/fprime/STest/STest/Scenario/ConditionalScenario.hpp | // ======================================================================
// \title ConditionalScenario.hpp
// \author bocchino
// \brief Run a scenario while a condition holds
//
// \copyright
// Copyright (C) 2017 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
// ======================================================================
#ifndef STest_ConditionalScenario_HPP
#define STest_ConditionalScenario_HPP
#include "STest/Scenario/Scenario.hpp"
namespace STest {
//! Run a scenario while a condition holds
template<typename State> class ConditionalScenario :
public Scenario<State>
{
public:
// ----------------------------------------------------------------------
// Constructors and destructors
// ----------------------------------------------------------------------
//! Construct a ConditionalScenario
ConditionalScenario(
const char *const name, //!< The name of the ConditionalScenario
Scenario<State>& scenario //!< The scenario to run
) :
Scenario<State>(name),
scenario(scenario)
{
}
//! Destroy object ConditionalScenario
virtual ~ConditionalScenario() {
}
public:
// ----------------------------------------------------------------------
// Scenario implementation
// ----------------------------------------------------------------------
//! The virtual implementation of reset required by Scenario
void reset_Scenario() {
this->scenario.reset();
this->reset_ConditionalScenario();
}
//! The virtual implementation of nextRule required by Scenario
//! \return The next rule, assuming isDone() is false, or nullptr if none
Rule<State>* nextRule_Scenario(
State& state //!< The system state
) {
Rule<State>* rule = nullptr;
if (this->condition_ConditionalScenario(state)) {
rule = this->scenario.nextRule(state);
}
this->nextRule_ConditionalScenario(rule);
return rule;
}
//! The virtual implementation of isDone required by Scenario
//! \return Whether the scenario is done
bool isDone_Scenario() const {
return this->scenario.isDone();
}
protected:
// ----------------------------------------------------------------------
// Protected virtual methods
// ----------------------------------------------------------------------
//! The virtual condition required by ConditionalScenario
//! \return Whether the condition holds
virtual bool condition_ConditionalScenario(
const State& state //!< The system state
) const = 0;
//! The virtual implementation of nextRule required by ConditionalScenario
virtual void nextRule_ConditionalScenario(
const Rule<State> *const nextRule //!< The next rule
) = 0;
//! The virtual implementation of reset required by ConditionalScenario
virtual void reset_ConditionalScenario() = 0;
protected:
// ----------------------------------------------------------------------
// Protected member variables
// ----------------------------------------------------------------------
//! The scenario to run
Scenario<State>& scenario;
};
}
#endif
| hpp |
fprime | data/projects/fprime/STest/STest/Scenario/SelectedScenario.hpp | // ======================================================================
// \title SelectedScenario.hpp
// \author bocchino
// \brief Randomly select a scenario and run it
//
// \copyright
// Copyright (C) 2017 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
// ======================================================================
#ifndef STest_SelectedScenario_HPP
#define STest_SelectedScenario_HPP
#include <cassert>
#include <cstring>
#include "STest/Random/Random.hpp"
#include "STest/Scenario/Scenario.hpp"
#include "STest/Scenario/ScenarioArray.hpp"
namespace STest {
//! Randomly select a scenario and run it
template<typename State> class SelectedScenario :
public Scenario<State>
{
public:
// ----------------------------------------------------------------------
// Constructors and destructors
// ----------------------------------------------------------------------
//! Construct a SelectedScenario object
SelectedScenario(
const char *const name, //!< The name of the scenario
Scenario<State>** scenarios, //!< The scenarios in the array
const U32 size //!< The size of the array
) :
Scenario<State>(name),
scenarioArray(new ScenarioArray<State>(scenarios, size)),
selectedScenario(nullptr),
seen(new bool[size])
{
}
//! Destroy a SelectedScenario object
virtual ~SelectedScenario() {
if (this->scenarioArray != nullptr) {
delete this->scenarioArray;
}
if (this->seen != nullptr) {
delete[] this->seen;
}
}
public:
// ----------------------------------------------------------------------
// Scenario implementation
// ----------------------------------------------------------------------
//! The virtual implementation of reset required by Scenario
void reset_Scenario() {
this->selectedScenario = nullptr;
assert(this->scenarioArray != nullptr);
this->scenarioArray->reset();
}
//! The virtual implementation of nextRule required by Scenario
//! \return The next rule, assuming isDone() is false, or nullptr if none
Rule<State>* nextRule_Scenario(
State& state //!< The system state
) {
Rule<State>* rule = nullptr;
if (this->selectedScenario == nullptr) {
rule = this->selectScenario(state);
}
else {
rule = this->selectedScenario->nextRule(state);
}
return rule;
}
//! The virtual implementation of isDone required by Scenario
//! \return Whether the scenario is done
bool isDone_Scenario() const {
bool result = true;
if (this->selectedScenario != nullptr) {
result = this->selectedScenario->isDone();
}
else {
Scenario<State>* *const scenarios =
this->scenarioArray->getScenarios();
assert(scenarios != nullptr);
for (U32 i = 0; i < scenarioArray->size; ++i) {
assert(scenarios[i] != nullptr);
if (!scenarios[i]->isDone()) {
result = false;
break;
}
}
}
return result;
}
private:
// ----------------------------------------------------------------------
// Private helper methods
// ----------------------------------------------------------------------
//! Select a scenario and return a rule from it
//! \return The rule
Rule<State>* selectScenario(
State& state //!< The system state
) {
Rule<State>* rule = nullptr;
const U32 size = this->scenarioArray->size;
memset(this->seen, 0, size * sizeof(bool));
U32 numSeen = 0;
assert(this->scenarioArray != nullptr);
Scenario<State> **const scenarios =
this->scenarioArray->getScenarios();
assert(scenarios != nullptr);
while (numSeen < size) {
const U32 i = this->scenarioArray->getRandomIndex();
if (this->seen[i]) {
continue;
}
Scenario<State> *const scenario = scenarios[i];
assert(scenario != nullptr);
rule = scenario->nextRule(state);
if (rule != nullptr) {
this->selectedScenario = scenario;
break;
}
this->seen[i] = true;
++numSeen;
}
return rule;
}
private:
// ----------------------------------------------------------------------
// Private member variables
// ----------------------------------------------------------------------
//! ScenarioArray containing the scenarios to select
ScenarioArray<State>* scenarioArray;
//! The selected scenario
Scenario<State>* selectedScenario;
//! An array to store the scenarios seen
bool* seen;
};
}
#endif
| hpp |
fprime | data/projects/fprime/STest/STest/Scenario/BoundedIteratedScenario.hpp | // ======================================================================
// \title BoundedIteratedScenario.hpp
// \author bocchino
// \brief Run an iterated scenario, bounding the number of iterations
//
// \copyright
// Copyright (C) 2017 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
// ======================================================================
#ifndef STest_BoundedIteratedScenario_HPP
#define STest_BoundedIteratedScenario_HPP
#include "STest/Scenario/ConditionalIteratedScenario.hpp"
namespace STest {
//! Run a scenario, bounding the number of iterations
template<typename State> class BoundedIteratedScenario :
public ConditionalIteratedScenario<State>
{
public:
// ----------------------------------------------------------------------
// Constructors and destructors
// ----------------------------------------------------------------------
//! Construct a BoundedIteratedScenario
BoundedIteratedScenario(
const char *const name, //!< The name of the BoundedIteratedScenario
IteratedScenario<State>& scenario, //!< The scenario to run
const U32 bound //!< The bound
) :
ConditionalIteratedScenario<State>(name, scenario),
numIterations(0),
bound(bound)
{
}
//! Destroy a BoundedIteratedScenario
virtual ~BoundedIteratedScenario() {
}
public:
// ----------------------------------------------------------------------
// ConditionalIteratedScenario implementation
// ----------------------------------------------------------------------
//! The virtual condition required by ConditionalIteratedScenario
//! \return Whether the condition holds
bool condition_ConditionalIteratedScenario(
const State& state //!< The system state
) const {
return this->numIterations < this->bound;
}
//! The virtual implementation of nextScenario required by ConditionalIteratedScenario
void nextScenario_ConditionalIteratedScenario(
const Scenario<State> *const nextScenario //!< The next scenario
) {
if (nextScenario != nullptr) {
++this->numIterations;
}
}
private:
// ----------------------------------------------------------------------
// Private member variables
// ----------------------------------------------------------------------
//! The number of iterations
U32 numIterations;
//! The bound on the number of iterations
const U32 bound;
};
}
#endif
| hpp |
fprime | data/projects/fprime/STest/STest/Scenario/IteratedScenario.hpp | // ======================================================================
// \title IteratedScenario.hpp
// \author bocchino
// \brief Iterate over a collection of scenarios
//
// \copyright
// Copyright (C) 2017 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
// ======================================================================
#ifndef STest_IteratedScenario_HPP
#define STest_IteratedScenario_HPP
#include <cassert>
#include "STest/Scenario/Scenario.hpp"
namespace STest {
//! Iterate over a collection of scenarios
template<typename State> class IteratedScenario :
public Scenario<State>
{
public:
// ----------------------------------------------------------------------
// Constructors and destructors
// ----------------------------------------------------------------------
//! Construct an IteratedScenario
IteratedScenario(
const char *const name //!< The name of the scenario
) :
Scenario<State>(name),
currentScenario(nullptr)
{
}
//! Destroy an IteratedScenario
virtual ~IteratedScenario() {
}
public:
// ----------------------------------------------------------------------
// Public instance methods
// ----------------------------------------------------------------------
//! Return the next scenario to run
//! \return The next scenario, assuming isDone() is false, or nullptr if none
Scenario<State>* nextScenario(
State& state //!< The system state
) {
Scenario<State> *scenario = nullptr;
if (!this->isDone()) {
scenario = this->nextScenario_IteratedScenario(state);
}
if (scenario != nullptr) {
scenario->reset();
}
return scenario;
}
public:
// ----------------------------------------------------------------------
// Scenario implementation
// ----------------------------------------------------------------------
//! The virtual implementation of reset required by Scenario
void reset_Scenario() {
this->currentScenario = nullptr;
this->reset_IteratedScenario();
}
//! The virtual implementation of nextRule required by Scenario
//! \return The next rule, assuming isDone() is false, or nullptr if none
Rule<State>* nextRule_Scenario(
State& state //!< The system state
) {
Rule<State>* rule = nullptr;
if (this->currentScenario == nullptr) {
this->currentScenario = this->nextScenario(state);
}
if (this->currentScenario != nullptr) {
rule = this->currentScenario->nextRule(state);
}
while (
this->currentScenario != nullptr and
this->currentScenario->isDone() and
rule == nullptr
) {
this->currentScenario = this->nextScenario(state);
if (this->currentScenario != nullptr) {
rule = this->currentScenario->nextRule(state);
}
}
return rule;
}
//! The virtual implementation of isDone required by Scenario
//! \return Whether the scenario is done
bool isDone_Scenario() const {
return this->isDone_IteratedScenario();
}
protected:
// ----------------------------------------------------------------------
// Protected virtual methods
// ----------------------------------------------------------------------
//! The virtual implementation of reset required by IteratedScenario
virtual void reset_IteratedScenario() = 0;
//! The virtual implementation of nextScenario required by IteratedScenario
//! \return The next scenario, assuming isDone() is false, or nullptr if none
virtual Scenario<State>* nextScenario_IteratedScenario(
State& state //!< The system state
) = 0;
//! The virtual implementation of isDone required by IteratedScenario
//! \return Whether the scenario is done
virtual bool isDone_IteratedScenario() const = 0;
private:
// ----------------------------------------------------------------------
// Private member variables
// ----------------------------------------------------------------------
//! The current scenario in the iteration
Scenario<State>* currentScenario;
};
}
#endif
| hpp |
fprime | data/projects/fprime/STest/STest/Scenario/RandomScenario.hpp | // ======================================================================
// \title RandomScenario.hpp
// \author bocchino
// \brief Apply rules in a random sequence
//
// \copyright
// Copyright (C) 2017 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
// ======================================================================
#ifndef STest_RandomScenario_HPP
#define STest_RandomScenario_HPP
#include "STest/Scenario/InterleavedScenario.hpp"
#include "STest/Scenario/RepeatedRuleScenario.hpp"
namespace STest {
//! Apply rules in a random sequence
template<typename State> class RandomScenario :
public InterleavedScenario<State>
{
public:
// ----------------------------------------------------------------------
// Constructors and destructors
// ----------------------------------------------------------------------
//! Construct a RandomScenario from an array of rules
RandomScenario(
const char *const name, //!< The name of the scenario
Rule<State>** rules, //!< The rules in the array
const U32 size //!< The size of the array
) :
InterleavedScenario<State>(name, new Scenario<State>*[size], size)
{
assert(this->scenarioArray != nullptr);
Scenario<State>** scenarios = this->scenarioArray->getScenarios();
assert(scenarios != nullptr);
for (U32 i = 0; i < size; ++i) {
scenarios[i] = new RepeatedRuleScenario<State>(*rules[i]);
}
}
//! Destroy a RandomScenario
~RandomScenario() {
assert(this->scenarioArray != nullptr);
Scenario<State>** scenarios = this->scenarioArray->getScenarios();
assert(scenarios != nullptr);
for (U32 i = 0; i < this->scenarioArray->size; ++i) {
assert(scenarios[i] != nullptr);
delete scenarios[i];
}
delete[] scenarios;
}
};
}
#endif
| hpp |
fprime | data/projects/fprime/STest/STest/Scenario/RuleSequenceScenario.hpp | // ======================================================================
// \title RuleSequenceScenario.hpp
// \author bocchino
// \brief Apply a fixed sequence of rules
//
// \copyright
// Copyright (C) 2017 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
// ======================================================================
#ifndef STest_RuleSequenceScenario_HPP
#define STest_RuleSequenceScenario_HPP
#include <cassert>
#include "STest/Scenario/SequenceScenario.hpp"
#include "STest/Scenario/RuleScenario.hpp"
namespace STest {
//! \brief Apply a fixed sequence of rules
template<typename State> class RuleSequenceScenario :
public SequenceScenario<State>
{
public:
// ----------------------------------------------------------------------
// Constructors and destructors
// ----------------------------------------------------------------------
//! Construct a RuleSequenceScenario from an array of rules
RuleSequenceScenario(
const char *const name, //!< The name of the scenario
Rule<State>** rules, //!< The rules in the array
const U32 size //!< The size of the array
) :
SequenceScenario<State>(name, new Scenario<State>*[size], size)
{
assert(this->scenarioArray != nullptr);
Scenario<State>* *const scenarios = this->scenarioArray->getScenarios();
assert(scenarios != nullptr);
for (U32 i = 0; i < size; ++i) {
scenarios[i] = new RuleScenario<State>(*rules[i]);
}
}
//! Destroy object RuleSequenceScenario
~RuleSequenceScenario() {
assert(this->scenarioArray != nullptr);
Scenario<State>* *const scenarios = this->scenarioArray->getScenarios();
assert(scenarios != nullptr);
for (U32 i = 0; i < this->scenarioArray->size; ++i) {
assert(scenarios[i] != nullptr);
delete scenarios[i];
}
delete scenarios;
}
};
}
#endif
| hpp |
fprime | data/projects/fprime/STest/STest/Scenario/RepeatedScenario.hpp | // ======================================================================
// \title RepeatedScenario.hpp
// \author bocchino
// \brief Repeat a scenario
//
// \copyright
// Copyright (C) 2017 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
// ======================================================================
#ifndef STest_RepeatedScenario_HPP
#define STest_RepeatedScenario_HPP
#include "STest/Scenario/IteratedScenario.hpp"
namespace STest {
//! \brief Repeat a scenario
template<typename State> class RepeatedScenario :
public IteratedScenario<State>
{
public:
// ----------------------------------------------------------------------
// Constructors and destructors
// ----------------------------------------------------------------------
//! Construct a RepeatedScenario
RepeatedScenario(
const char *const name, //!< The name of the scenario
Scenario<State>& scenario //!< The scenario to repeat
) :
IteratedScenario<State>(name),
scenario(scenario),
done(false)
{
}
public:
// ----------------------------------------------------------------------
// IteratedScenario implementation
// ----------------------------------------------------------------------
//! The virtual implementation of reset required by IteratedScenario
void reset_IteratedScenario() {
this->scenario.reset();
this->done = scenario.isDone();
}
//! The virtual implementation of nextScenario required by IteratedScenario
//! \return The next scenario, assuming isDone() is false, or nullptr if none
Scenario<State>* nextScenario_IteratedScenario(
State& state //!< The system state
) {
return &this->scenario;
}
//! The virtual implementation of isDone required by IteratedScenario
//! \return Whether the scenario is done
bool isDone_IteratedScenario() const {
return this->done;
}
protected:
// ----------------------------------------------------------------------
// Protected member variables
// ----------------------------------------------------------------------
//! The scenario to repeat
Scenario<State>& scenario;
//! Whether the iterated scenario is done
bool done;
};
}
#endif
| hpp |
fprime | data/projects/fprime/STest/STest/types/basic_types.h | // ======================================================================
// \title basic_types.h
// \author bocchino
// \brief STest basic types
//
// \copyright
// Copyright (C) 2017 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
// ======================================================================
#ifndef STEST_BASIC_TYPES_H
#define STEST_BASIC_TYPES_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
typedef double F64;
typedef float F32;
typedef int16_t I16;
typedef int32_t I32;
typedef int64_t I64;
typedef int8_t I8;
typedef uint16_t U16;
typedef uint32_t U32;
typedef uint64_t U64;
typedef uint8_t U8;
#ifdef __cplusplus
}
#endif
#endif
| h |
fprime | data/projects/fprime/STest/STest/Rule/Rule.hpp | // ======================================================================
// \title Rule.hpp
// \author bocchino
// \brief Rule interface for scenario testing
//
// \copyright
// Copyright (C) 2017 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
// ======================================================================
#ifndef STest_Rule_HPP
#define STest_Rule_HPP
#include "STest/testing.hpp"
#include "STest/types/basic_types.h"
namespace STest {
template<typename State> class Rule {
public:
// ----------------------------------------------------------------------
// Constructors and destructors
// ----------------------------------------------------------------------
//! Construct object Rule
Rule(
const char *const name //!< The name of the rule
) :
m_name(name)
{
}
//! Destroy object Rule
virtual ~Rule() {
}
public:
// ----------------------------------------------------------------------
// Public instance methods
// ----------------------------------------------------------------------
//! Apply the rule
void apply(
State& state //!< The system state
) {
ASSERT_TRUE(this->precondition(state))
<< "precondition failed applying rule " << this->m_name;
this->action(state);
}
//! Evaluate the precondition associated with the rule
//! \return Whether the condition holds
virtual bool precondition(
const State& state //!< The system state
) = 0;
//! Get rule name
char const * getName() const {
return this->m_name;
}
protected:
// ----------------------------------------------------------------------
// Protected instance methods
// ----------------------------------------------------------------------
//! Perform the action associated with the rule
virtual void action(
State& state //!< The system state
) = 0;
public:
// ----------------------------------------------------------------------
// Public member variables
// ----------------------------------------------------------------------
private:
// ----------------------------------------------------------------------
// Private member variables
// ----------------------------------------------------------------------
//! The name of the rule
const char *const m_name;
};
}
#endif
| hpp |
fprime | data/projects/fprime/STest/STest/Random/Random.hpp | // ======================================================================
// \title Random.hpp
// \author bocchino
// \brief Random number generation
//
// \copyright
// Copyright (C) 2017 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
// ======================================================================
#ifndef STest_Random_HPP
#define STest_Random_HPP
#include <limits.h>
#include <sys/time.h>
#include "STest/types/basic_types.h"
namespace STest {
namespace Random {
enum {
//! The maximum value of a random number
MAX_VALUE = INT_MAX
};
namespace SeedValue {
//! Get a seed value from the system time
U32 getFromTime();
//! Get a seed value from file
//! \return true on success, false on failure
bool getFromFile(
const char *const fileName, //!< The file name
U32& value //!< The seed value
);
//! Set the seed value
void set(
const U32 value //!< The seed value
);
//! Append a seed value to a file
bool appendToFile(
const char *const fileName, //!< The file name
const U32 seedValue //!< The seed value
);
}
//! Seed the random number generator:
//! 1. Get the seed value from the file "seed" if possible, otherwise
//! from the current time.
//! 2. Set the seed value.
//! 3. Append the seed value to the file "seed-history"
void seed();
//! Return a random number in the range given by [start, start + length - 1].
//! For example, Random::startLength(5, 3) returns a number
//! between 5 and 7, inclusive.
//! \return The number
U32 startLength(
const U32 start, //!< The start value of the range
const U32 length //!< the length of the range, including the start and end values
);
//! Return a random number between the lower and the upper bound.
//! For example, Random::lowerUpper(3, 5) returns a number
//! between 3 and 5, inclusive.
//! \return The number
U32 lowerUpper(
const U32 lower, //!< The lower bound
const U32 upper //!< The upper bound
);
//! Return a random number in the interval [0, 1]
double inUnitInterval();
}
}
#endif
| hpp |
fprime | data/projects/fprime/STest/STest/Random/bsd_random.c | /*
* Copyright (c) 1983, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include "bsd_random.h"
/*
* random.c:
*
* An improved random number generation package. In addition to the standard
* rand()/srand() like interface, this package also has a special state info
* interface. The initstate() routine is called with a seed, an array of
* bytes, and a count of how many bytes are being passed in; this array is
* then initialized to contain information for random number generation with
* that much state information. Good sizes for the amount of state
* information are 32, 64, 128, and 256 bytes. The state can be switched by
* calling the setstate() routine with the same array as was initialized
* with initstate(). By default, the package runs with 128 bytes of state
* information and generates far better random numbers than a linear
* congruential generator. If the amount of state information is less than
* 32 bytes, a simple linear congruential R.N.G. is used.
*
* Internally, the state information is treated as an array of uint32_t's; the
* zeroeth element of the array is the type of R.N.G. being used (small
* integer); the remainder of the array is the state information for the
* R.N.G. Thus, 32 bytes of state information will give 7 ints worth of
* state information, which will allow a degree seven polynomial. (Note:
* the zeroeth word of state information also has some other information
* stored in it -- see setstate() for details).
*
* The random number generation technique is a linear feedback shift register
* approach, employing trinomials (since there are fewer terms to sum up that
* way). In this approach, the least significant bit of all the numbers in
* the state table will act as a linear feedback shift register, and will
* have period 2^deg - 1 (where deg is the degree of the polynomial being
* used, assuming that the polynomial is irreducible and primitive). The
* higher order bits will have longer periods, since their values are also
* influenced by pseudo-random carries out of the lower bits. The total
* period of the generator is approximately deg*(2**deg - 1); thus doubling
* the amount of state information has a vast influence on the period of the
* generator. Note: the deg*(2**deg - 1) is an approximation only good for
* large deg, when the period of the shift is the dominant factor.
* With deg equal to seven, the period is actually much longer than the
* 7*(2**7 - 1) predicted by this formula.
*
* Modified 28 December 1994 by Jacob S. Rosenberg.
* The following changes have been made:
* All references to the type u_int have been changed to unsigned long.
* All references to type int have been changed to type long. Other
* cleanups have been made as well. A warning for both initstate and
* setstate has been inserted to the effect that on Sparc platforms
* the 'arg_state' variable must be forced to begin on word boundaries.
* This can be easily done by casting a long integer array to char *.
* The overall logic has been left STRICTLY alone. This software was
* tested on both a VAX and Sun SparcStation with exactly the same
* results. The new version and the original give IDENTICAL results.
* The new version is somewhat faster than the original. As the
* documentation says: "By default, the package runs with 128 bytes of
* state information and generates far better random numbers than a linear
* congruential generator. If the amount of state information is less than
* 32 bytes, a simple linear congruential R.N.G. is used." For a buffer of
* 128 bytes, this new version runs about 19 percent faster and for a 16
* byte buffer it is about 5 percent faster.
*/
/*
* For each of the currently supported random number generators, we have a
* break value on the amount of state information (you need at least this
* many bytes of state info to support this random number generator), a degree
* for the polynomial (actually a trinomial) that the R.N.G. is based on, and
* the separation between the two lower order coefficients of the trinomial.
*/
#define TYPE_0 0 /* linear congruential */
#define BREAK_0 8
#define DEG_0 0
#define SEP_0 0
#define TYPE_1 1 /* x**7 + x**3 + 1 */
#define BREAK_1 32
#define DEG_1 7
#define SEP_1 3
#define TYPE_2 2 /* x**15 + x + 1 */
#define BREAK_2 64
#define DEG_2 15
#define SEP_2 1
#define TYPE_3 3 /* x**31 + x**3 + 1 */
#define BREAK_3 128
#define DEG_3 31
#define SEP_3 3
#define TYPE_4 4 /* x**63 + x + 1 */
#define BREAK_4 256
#define DEG_4 63
#define SEP_4 1
/*
* Array versions of the above information to make code run faster --
* relies on fact that TYPE_i == i.
*/
#define MAX_TYPES 5 /* max number of types above */
#define NSHUFF 50 /* to drop some "seed -> 1st value" linearity */
static const int degrees[MAX_TYPES] = { DEG_0, DEG_1, DEG_2, DEG_3, DEG_4 };
static const int seps [MAX_TYPES] = { SEP_0, SEP_1, SEP_2, SEP_3, SEP_4 };
/*
* Initially, everything is set up as if from:
*
* initstate(1, randtbl, 128);
*
* Note that this initialization takes advantage of the fact that srandom()
* advances the front and rear pointers 10*rand_deg times, and hence the
* rear pointer which starts at 0 will also end up at zero; thus the zeroeth
* element of the state information, which contains info about the current
* position of the rear pointer is just
*
* MAX_TYPES * (rptr - state) + TYPE_3 == TYPE_3.
*/
static uint32_t randtbl[DEG_3 + 1] = {
TYPE_3,
0x991539b1, 0x16a5bce3, 0x6774a4cd, 0x3e01511e, 0x4e508aaa, 0x61048c05,
0xf5500617, 0x846b7115, 0x6a19892c, 0x896a97af, 0xdb48f936, 0x14898454,
0x37ffd106, 0xb58bff9c, 0x59e17104, 0xcf918a49, 0x09378c83, 0x52c7a471,
0x8d293ea9, 0x1f4fc301, 0xc3db71be, 0x39b44e1c, 0xf8a44ef9, 0x4c8b80b1,
0x19edc328, 0x87bf4bdd, 0xc9b240e5, 0xe9ee4b1b, 0x4382aee7, 0x535b6b41,
0xf3bec5da
};
/*
* fptr and rptr are two pointers into the state info, a front and a rear
* pointer. These two pointers are always rand_sep places apart, as they
* cycle cyclically through the state information. (Yes, this does mean we
* could get away with just one pointer, but the code for random() is more
* efficient this way). The pointers are left positioned as they would be
* from the call
*
* initstate(1, randtbl, 128);
*
* (The position of the rear pointer, rptr, is really 0 (as explained above
* in the initialization of randtbl) because the state table pointer is set
* to point to randtbl[1] (as explained below).
*/
static uint32_t *fptr = &randtbl[SEP_3 + 1];
static uint32_t *rptr = &randtbl[1];
/*
* The following things are the pointer to the state information table, the
* type of the current generator, the degree of the current polynomial being
* used, and the separation between the two pointers. Note that for efficiency
* of random(), we remember the first location of the state information, not
* the zeroeth. Hence it is valid to access state[-1], which is used to
* store the type of the R.N.G. Also, we remember the last location, since
* this is more efficient than indexing every time to find the address of
* the last element to see if the front and rear pointers have wrapped.
*/
static uint32_t *state = &randtbl[1];
static int rand_type = TYPE_3;
static int rand_deg = DEG_3;
static int rand_sep = SEP_3;
static uint32_t *end_ptr = &randtbl[DEG_3 + 1];
static inline uint32_t good_rand(int32_t) __attribute__((always_inline));
static inline uint32_t good_rand (int32_t x)
{
/*
* Compute x = (7^5 * x) mod (2^31 - 1)
* without overflowing 31 bits:
* (2^31 - 1) = 127773 * (7^5) + 2836
* From "Random number generators: good ones are hard to find",
* Park and Miller, Communications of the ACM, vol. 31, no. 10,
* October 1988, p. 1195.
*/
int32_t hi, lo;
/* Can't be initialized with 0, so use another value. */
if (x == 0)
x = 123459876;
hi = x / 127773;
lo = x % 127773;
x = 16807 * lo - 2836 * hi;
if (x < 0)
x += 0x7fffffff;
return (x);
}
/*
* srandom:
*
* Initialize the random number generator based on the given seed. If the
* type is the trivial no-state-information type, just remember the seed.
* Otherwise, initializes state[] based on the given "seed" via a linear
* congruential generator. Then, the pointers are set to known locations
* that are exactly rand_sep places apart. Lastly, it cycles the state
* information a given number of times to get rid of any initial dependencies
* introduced by the L.C.R.N.G. Note that the initialization of randtbl[]
* for default usage relies on values produced by this routine.
*/
void
bsd_srandom(unsigned x)
{
int i, lim;
state[0] = (uint32_t)x;
if (rand_type == TYPE_0)
lim = NSHUFF;
else {
for (i = 1; i < rand_deg; i++)
state[i] = good_rand(state[i - 1]);
fptr = &state[rand_sep];
rptr = &state[0];
lim = 10 * rand_deg;
}
for (i = 0; i < lim; i++)
(void)bsd_random();
}
/*
* initstate:
*
* Initialize the state information in the given array of n bytes for future
* random number generation. Based on the number of bytes we are given, and
* the break values for the different R.N.G.'s, we choose the best (largest)
* one we can and set things up for it. srandom() is then called to
* initialize the state information.
*
* Note that on return from srandom(), we set state[-1] to be the type
* multiplexed with the current value of the rear pointer; this is so
* successive calls to initstate() won't lose this information and will be
* able to restart with setstate().
*
* Note: the first thing we do is save the current state, if any, just like
* setstate() so that it doesn't matter when initstate is called.
*
* Returns a pointer to the old state.
*
* Note: The Sparc platform requires that arg_state begin on an int
* word boundary; otherwise a bus error will occur. Even so, lint will
* complain about mis-alignment, but you should disregard these messages.
*/
char *
bsd_initstate(
unsigned seed, /* seed for R.N.G. */
char *arg_state, /* pointer to state array */
size_t n /* # bytes of state info */
) {
char *ostate = (char *)(&state[-1]);
uint32_t *int_arg_state = (uint32_t *)arg_state;
if (rand_type == TYPE_0)
state[-1] = rand_type;
else
state[-1] = MAX_TYPES * (rptr - state) + rand_type;
if (n < BREAK_0) {
(void)fprintf(stderr,
"random: not enough state (%zd bytes); ignored.\n", n);
return(0);
}
if (n < BREAK_1) {
rand_type = TYPE_0;
rand_deg = DEG_0;
rand_sep = SEP_0;
} else if (n < BREAK_2) {
rand_type = TYPE_1;
rand_deg = DEG_1;
rand_sep = SEP_1;
} else if (n < BREAK_3) {
rand_type = TYPE_2;
rand_deg = DEG_2;
rand_sep = SEP_2;
} else if (n < BREAK_4) {
rand_type = TYPE_3;
rand_deg = DEG_3;
rand_sep = SEP_3;
} else {
rand_type = TYPE_4;
rand_deg = DEG_4;
rand_sep = SEP_4;
}
state = int_arg_state + 1; /* first location */
end_ptr = &state[rand_deg]; /* must set end_ptr before srandom */
bsd_srandom(seed);
if (rand_type == TYPE_0)
int_arg_state[0] = rand_type;
else
int_arg_state[0] = MAX_TYPES * (rptr - state) + rand_type;
return(ostate);
}
/*
* setstate:
*
* Restore the state from the given state array.
*
* Note: it is important that we also remember the locations of the pointers
* in the current state information, and restore the locations of the pointers
* from the old state information. This is done by multiplexing the pointer
* location into the zeroeth word of the state information.
*
* Note that due to the order in which things are done, it is OK to call
* setstate() with the same state as the current state.
*
* Returns a pointer to the old state information.
*
* Note: The Sparc platform requires that arg_state begin on an int
* word boundary; otherwise a bus error will occur. Even so, lint will
* complain about mis-alignment, but you should disregard these messages.
*/
char *
bsd_setstate(
const char *arg_state /* pointer to state array */
) {
uint32_t *new_state = (uint32_t *)arg_state;
uint32_t type = new_state[0] % MAX_TYPES;
uint32_t rear = new_state[0] / MAX_TYPES;
char *ostate = (char *)(&state[-1]);
if (rand_type == TYPE_0)
state[-1] = rand_type;
else
state[-1] = MAX_TYPES * (rptr - state) + rand_type;
switch(type) {
case TYPE_0:
case TYPE_1:
case TYPE_2:
case TYPE_3:
case TYPE_4:
rand_type = type;
rand_deg = degrees[type];
rand_sep = seps[type];
break;
default:
(void)fprintf(stderr,
"random: state info corrupted; not changed.\n");
}
state = new_state + 1;
if (rand_type != TYPE_0) {
rptr = &state[rear];
fptr = &state[(rear + rand_sep) % rand_deg];
}
end_ptr = &state[rand_deg]; /* set end_ptr too */
return(ostate);
}
/*
* random:
*
* If we are using the trivial TYPE_0 R.N.G., just do the old linear
* congruential bit. Otherwise, we do our fancy trinomial stuff, which is
* the same in all the other cases due to all the global variables that have
* been set up. The basic operation is to add the number at the rear pointer
* into the one at the front pointer. Then both pointers are advanced to
* the next location cyclically in the table. The value returned is the sum
* generated, reduced to 31 bits by throwing away the "least random" low bit.
*
* Note: the code takes advantage of the fact that both the front and
* rear pointers can't wrap on the same call by not testing the rear
* pointer if the front one has wrapped.
*
* Returns a 31-bit random number.
*/
long
bsd_random(void)
{
uint32_t i;
uint32_t *f, *r;
if (rand_type == TYPE_0) {
i = state[0];
state[0] = i = (good_rand(i)) & 0x7fffffff;
} else {
/*
* Use local variables rather than static variables for speed.
*/
f = fptr; r = rptr;
*f += *r;
i = (*f >> 1) & 0x7fffffff; /* chucking least random bit */
if (++f >= end_ptr) {
f = state;
++r;
}
else if (++r >= end_ptr) {
r = state;
}
fptr = f; rptr = r;
}
return((long)i);
}
| c |
fprime | data/projects/fprime/STest/STest/Random/bsd_random.h | // ======================================================================
// \title bsd_random.h
// \author See bsd_random.c
// \brief BSD random number generator
//
// \copyright
// Copyright (C) 2017 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
// ======================================================================
#include <sys/cdefs.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
void bsd_srandom(unsigned x);
char *bsd_initstate(unsigned seed, char *arg_state, size_t n);
char *bsd_setstate(const char *arg_state);
long bsd_random(void);
| h |
fprime | data/projects/fprime/STest/STest/Random/Random.cpp | // ======================================================================
// \title Random.cpp
// \author bocchino
// \brief Random number generation
//
// \copyright
// Copyright (C) 2017-2022 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
// ======================================================================
#include <cassert>
#include <cinttypes>
#include <ctime>
#include "STest/Random/Random.hpp"
extern "C" {
#include "STest/Random/bsd_random.h"
}
namespace STest {
namespace Random {
namespace SeedValue {
U32 getFromTime() {
struct timeval tv;
(void) gettimeofday(&tv, nullptr);
return tv.tv_usec;
}
bool getFromFile(
const char *const fileName,
U32& value
) {
bool result = false;
FILE *fp = fopen(fileName, "r");
if (fp != nullptr) {
result = (fscanf(fp, "%" PRIu32, &value) == 1);
(void) fclose(fp);
}
return result;
}
void set(const U32 value) {
bsd_srandom(value);
}
bool appendToFile(
const char *const fileName,
const U32 seedValue
) {
bool result = false;
FILE *fp = fopen(fileName, "a");
if (fp != nullptr) {
int status = fprintf(
fp,
"%" PRIu32 "\n",
seedValue
);
result = (status > 0);
(void) fclose(fp);
}
return result;
}
}
void seed() {
U32 seedValue = 0;
const bool seedValueOK =
SeedValue::getFromFile("seed", seedValue);
if (seedValueOK) {
(void) printf("[STest::Random] Read seed %" PRIu32 " from file\n", seedValue);
}
else {
seedValue = SeedValue::getFromTime();
(void) printf("[STest::Random] Generated seed %" PRIu32 " from system time\n", seedValue);
}
(void) SeedValue::appendToFile("seed-history", seedValue);
SeedValue::set(seedValue);
}
U32 startLength(
const U32 start,
const U32 length
) {
assert(length > 0);
return lowerUpper(start, start + length - 1);
}
U32 lowerUpper(
const U32 lower,
const U32 upper
) {
assert(lower <= upper);
const F64 length = static_cast<F64>(upper) - lower + 1;
const F64 randFloat = inUnitInterval() * length;
const U32 offset = static_cast<U32>(randFloat);
const U32 result = lower + offset;
// Handle boundary case where inUnitInterval returns 1.0
return (result <= upper) ? result : result - 1;
}
double inUnitInterval() {
const U32 randInt = bsd_random();
const F64 ratio = static_cast<F64>(randInt) / MAX_VALUE;
return ratio;
}
}
}
| cpp |
fprime | data/projects/fprime/STest/STest/Pick/Pick.cpp | // ======================================================================
// \title Pick.cpp
// \author bocchino
// \brief Pick implementation
//
// \copyright
// Copyright (C) 2022 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
// ======================================================================
#include "STest/Pick/Pick.hpp"
namespace STest {
namespace Pick {
U32 any() {
return lowerUpper(0, 0xFFFFFFFFU);
}
}
}
| cpp |
fprime | data/projects/fprime/STest/STest/Pick/Pick.hpp | // ======================================================================
// \title Pick.hpp
// \author bocchino
// \brief Pick interface
//
// \copyright
// Copyright (C) 2022 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
// ======================================================================
#ifndef STEST_PICK_HPP
#define STEST_PICK_HPP
#include "STest/types/basic_types.h"
#ifdef STEST_MODE_spin
#include "STest/Pick/Pick_spin.hpp"
#endif
namespace STest {
namespace Pick {
//! Pick a double value in the interval [0, 1]
double inUnitInterval();
//! Return a U32 value in the range given by [start, start + length - 1].
//! For example, startLength(5, 3) returns a number
//! between 5 and 7, inclusive.
//! \return The U32 value
U32 startLength(
const U32 start, //!< The start value of the range
const U32 length //!< The length of the range, including the start and end values
);
//! Return a U32 value between the lower and the upper bound.
//! For example, lowerUpper(3, 5) returns a number between 3 and 5,
//! inclusive.
//! \return The U32 value
U32 lowerUpper(
const U32 lower, //!< The lower bound
const U32 upper //!< The upper bound
);
//! Return an arbitrary U32 value
//! \return The U32 value
U32 any();
}
}
#endif
| hpp |
fprime | data/projects/fprime/STest/STest/Pick/Pick_default.cpp | // ======================================================================
// \title Pick_default.cpp
// \author bocchino
// \brief Pick_default implementation
//
// \copyright
// Copyright (C) 2022 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
// ======================================================================
#include "STest/Pick/Pick.hpp"
#include "STest/Random/Random.hpp"
namespace STest {
namespace Pick {
double inUnitInterval() {
return STest::Random::inUnitInterval();
}
U32 startLength(
const U32 start,
const U32 length
) {
return STest::Random::startLength(start, length);
}
U32 lowerUpper(
const U32 lower,
const U32 upper
) {
return STest::Random::lowerUpper(lower, upper);
}
}
}
| cpp |
asio | data/projects/asio/example/cpp14/echo/blocking_udp_echo_server.cpp | //
// blocking_udp_echo_server.cpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include <cstdlib>
#include <iostream>
#include <boost/asio/ts/buffer.hpp>
#include <boost/asio/ts/internet.hpp>
using boost::asio::ip::udp;
enum { max_length = 1024 };
void server(boost::asio::io_context& io_context, unsigned short port)
{
udp::socket sock(io_context, udp::endpoint(udp::v4(), port));
for (;;)
{
char data[max_length];
udp::endpoint sender_endpoint;
size_t length = sock.receive_from(
boost::asio::buffer(data, max_length), sender_endpoint);
sock.send_to(boost::asio::buffer(data, length), sender_endpoint);
}
}
int main(int argc, char* argv[])
{
try
{
if (argc != 2)
{
std::cerr << "Usage: blocking_udp_echo_server <port>\n";
return 1;
}
boost::asio::io_context io_context;
server(io_context, std::atoi(argv[1]));
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
| cpp |
asio | data/projects/asio/example/cpp14/echo/blocking_tcp_echo_client.cpp | //
// blocking_tcp_echo_client.cpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <boost/asio.hpp>
using boost::asio::ip::tcp;
enum { max_length = 1024 };
int main(int argc, char* argv[])
{
try
{
if (argc != 3)
{
std::cerr << "Usage: blocking_tcp_echo_client <host> <port>\n";
return 1;
}
boost::asio::io_context io_context;
tcp::socket s(io_context);
tcp::resolver resolver(io_context);
boost::asio::connect(s, resolver.resolve(argv[1], argv[2]));
std::cout << "Enter message: ";
char request[max_length];
std::cin.getline(request, max_length);
size_t request_length = std::strlen(request);
boost::asio::write(s, boost::asio::buffer(request, request_length));
char reply[max_length];
size_t reply_length = boost::asio::read(s,
boost::asio::buffer(reply, request_length));
std::cout << "Reply is: ";
std::cout.write(reply, reply_length);
std::cout << "\n";
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
| cpp |
asio | data/projects/asio/example/cpp14/echo/blocking_udp_echo_client.cpp | //
// blocking_udp_echo_client.cpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <boost/asio/ts/buffer.hpp>
#include <boost/asio/ts/internet.hpp>
using boost::asio::ip::udp;
enum { max_length = 1024 };
int main(int argc, char* argv[])
{
try
{
if (argc != 3)
{
std::cerr << "Usage: blocking_udp_echo_client <host> <port>\n";
return 1;
}
boost::asio::io_context io_context;
udp::socket s(io_context, udp::endpoint(udp::v4(), 0));
udp::resolver resolver(io_context);
udp::endpoint endpoint =
*resolver.resolve(udp::v4(), argv[1], argv[2]).begin();
std::cout << "Enter message: ";
char request[max_length];
std::cin.getline(request, max_length);
size_t request_length = std::strlen(request);
s.send_to(boost::asio::buffer(request, request_length), endpoint);
char reply[max_length];
udp::endpoint sender_endpoint;
size_t reply_length = s.receive_from(
boost::asio::buffer(reply, max_length), sender_endpoint);
std::cout << "Reply is: ";
std::cout.write(reply, reply_length);
std::cout << "\n";
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
| cpp |
asio | data/projects/asio/example/cpp14/echo/blocking_tcp_echo_server.cpp | //
// blocking_tcp_echo_server.cpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include <cstdlib>
#include <iostream>
#include <thread>
#include <utility>
#include <boost/asio/ts/buffer.hpp>
#include <boost/asio/ts/internet.hpp>
using boost::asio::ip::tcp;
const int max_length = 1024;
void session(tcp::socket sock)
{
try
{
for (;;)
{
char data[max_length];
boost::system::error_code error;
size_t length = sock.read_some(boost::asio::buffer(data), error);
if (error == boost::asio::stream_errc::eof)
break; // Connection closed cleanly by peer.
else if (error)
throw boost::system::system_error(error); // Some other error.
boost::asio::write(sock, boost::asio::buffer(data, length));
}
}
catch (std::exception& e)
{
std::cerr << "Exception in thread: " << e.what() << "\n";
}
}
void server(boost::asio::io_context& io_context, unsigned short port)
{
tcp::acceptor a(io_context, tcp::endpoint(tcp::v4(), port));
for (;;)
{
tcp::socket sock(io_context);
a.accept(sock);
std::thread(session, std::move(sock)).detach();
}
}
int main(int argc, char* argv[])
{
try
{
if (argc != 2)
{
std::cerr << "Usage: blocking_tcp_echo_server <port>\n";
return 1;
}
boost::asio::io_context io_context;
server(io_context, std::atoi(argv[1]));
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
| cpp |
asio | data/projects/asio/example/cpp14/echo/async_udp_echo_server.cpp | //
// async_udp_echo_server.cpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include <cstdlib>
#include <iostream>
#include <boost/asio/ts/buffer.hpp>
#include <boost/asio/ts/internet.hpp>
using boost::asio::ip::udp;
class server
{
public:
server(boost::asio::io_context& io_context, short port)
: socket_(io_context, udp::endpoint(udp::v4(), port))
{
do_receive();
}
void do_receive()
{
socket_.async_receive_from(
boost::asio::buffer(data_, max_length), sender_endpoint_,
[this](boost::system::error_code ec, std::size_t bytes_recvd)
{
if (!ec && bytes_recvd > 0)
{
do_send(bytes_recvd);
}
else
{
do_receive();
}
});
}
void do_send(std::size_t length)
{
socket_.async_send_to(
boost::asio::buffer(data_, length), sender_endpoint_,
[this](boost::system::error_code /*ec*/, std::size_t /*bytes_sent*/)
{
do_receive();
});
}
private:
udp::socket socket_;
udp::endpoint sender_endpoint_;
enum { max_length = 1024 };
char data_[max_length];
};
int main(int argc, char* argv[])
{
try
{
if (argc != 2)
{
std::cerr << "Usage: async_udp_echo_server <port>\n";
return 1;
}
boost::asio::io_context io_context;
server s(io_context, std::atoi(argv[1]));
io_context.run();
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
| cpp |
asio | data/projects/asio/example/cpp14/echo/async_tcp_echo_server.cpp | //
// async_tcp_echo_server.cpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include <cstdlib>
#include <iostream>
#include <memory>
#include <utility>
#include <boost/asio/ts/buffer.hpp>
#include <boost/asio/ts/internet.hpp>
using boost::asio::ip::tcp;
class session
: public std::enable_shared_from_this<session>
{
public:
session(tcp::socket socket)
: socket_(std::move(socket))
{
}
void start()
{
do_read();
}
private:
void do_read()
{
auto self(shared_from_this());
socket_.async_read_some(boost::asio::buffer(data_, max_length),
[this, self](boost::system::error_code ec, std::size_t length)
{
if (!ec)
{
do_write(length);
}
});
}
void do_write(std::size_t length)
{
auto self(shared_from_this());
boost::asio::async_write(socket_, boost::asio::buffer(data_, length),
[this, self](boost::system::error_code ec, std::size_t /*length*/)
{
if (!ec)
{
do_read();
}
});
}
tcp::socket socket_;
enum { max_length = 1024 };
char data_[max_length];
};
class server
{
public:
server(boost::asio::io_context& io_context, short port)
: acceptor_(io_context, tcp::endpoint(tcp::v4(), port)),
socket_(io_context)
{
do_accept();
}
private:
void do_accept()
{
acceptor_.async_accept(socket_,
[this](boost::system::error_code ec)
{
if (!ec)
{
std::make_shared<session>(std::move(socket_))->start();
}
do_accept();
});
}
tcp::acceptor acceptor_;
tcp::socket socket_;
};
int main(int argc, char* argv[])
{
try
{
if (argc != 2)
{
std::cerr << "Usage: async_tcp_echo_server <port>\n";
return 1;
}
boost::asio::io_context io_context;
server s(io_context, std::atoi(argv[1]));
io_context.run();
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
| cpp |
asio | data/projects/asio/example/cpp14/operations/c_callback_wrapper.cpp | //
// c_callback_wrapper.cpp
// ~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include <boost/asio.hpp>
#include <iostream>
#include <memory>
#include <new>
//------------------------------------------------------------------------------
// This is a mock implementation of a C-based API that uses the function pointer
// plus void* context idiom for exposing a callback.
void read_input(const char* prompt, void (*cb)(void*, const char*), void* arg)
{
std::thread(
[prompt = std::string(prompt), cb, arg]
{
std::cout << prompt << ": ";
std::cout.flush();
std::string line;
std::getline(std::cin, line);
cb(arg, line.c_str());
}).detach();
}
//------------------------------------------------------------------------------
// This is an asynchronous operation that wraps the C-based API.
// To map our completion handler into a function pointer / void* callback, we
// need to allocate some state that will live for the duration of the
// operation. A pointer to this state will be passed to the C-based API.
template <typename Handler>
class read_input_state
{
public:
read_input_state(Handler&& handler)
: handler_(std::move(handler)),
work_(boost::asio::make_work_guard(handler_))
{
}
// Create the state using the handler's associated allocator.
static read_input_state* create(Handler&& handler)
{
// A unique_ptr deleter that is used to destroy uninitialised objects.
struct deleter
{
// Get the handler's associated allocator type. If the handler does not
// specify an associated allocator, we will use a recycling allocator as
// the default. As the associated allocator is a proto-allocator, we must
// rebind it to the correct type before we can use it to allocate objects.
typename std::allocator_traits<
boost::asio::associated_allocator_t<Handler,
boost::asio::recycling_allocator<void>>>::template
rebind_alloc<read_input_state> alloc;
void operator()(read_input_state* ptr)
{
std::allocator_traits<decltype(alloc)>::deallocate(alloc, ptr, 1);
}
} d{boost::asio::get_associated_allocator(handler,
boost::asio::recycling_allocator<void>())};
// Allocate memory for the state.
std::unique_ptr<read_input_state, deleter> uninit_ptr(
std::allocator_traits<decltype(d.alloc)>::allocate(d.alloc, 1), d);
// Construct the state into the newly allocated memory. This might throw.
read_input_state* ptr =
new (uninit_ptr.get()) read_input_state(std::move(handler));
// Release ownership of the memory and return the newly allocated state.
uninit_ptr.release();
return ptr;
}
static void callback(void* arg, const char* result)
{
read_input_state* self = static_cast<read_input_state*>(arg);
// A unique_ptr deleter that is used to destroy initialised objects.
struct deleter
{
// Get the handler's associated allocator type. If the handler does not
// specify an associated allocator, we will use a recycling allocator as
// the default. As the associated allocator is a proto-allocator, we must
// rebind it to the correct type before we can use it to allocate objects.
typename std::allocator_traits<
boost::asio::associated_allocator_t<Handler,
boost::asio::recycling_allocator<void>>>::template
rebind_alloc<read_input_state> alloc;
void operator()(read_input_state* ptr)
{
std::allocator_traits<decltype(alloc)>::destroy(alloc, ptr);
std::allocator_traits<decltype(alloc)>::deallocate(alloc, ptr, 1);
}
} d{boost::asio::get_associated_allocator(self->handler_,
boost::asio::recycling_allocator<void>())};
// To conform to the rules regarding asynchronous operations and memory
// allocation, we must make a copy of the state and deallocate the memory
// before dispatching the completion handler.
std::unique_ptr<read_input_state, deleter> state_ptr(self, d);
read_input_state state(std::move(*self));
state_ptr.reset();
// Dispatch the completion handler through the handler's associated
// executor, using the handler's associated allocator.
boost::asio::dispatch(state.work_.get_executor(),
boost::asio::bind_allocator(d.alloc,
[
handler = std::move(state.handler_),
result = std::string(result)
]() mutable
{
std::move(handler)(result);
}));
}
private:
Handler handler_;
// According to the rules for asynchronous operations, we need to track
// outstanding work against the handler's associated executor until the
// asynchronous operation is complete.
boost::asio::executor_work_guard<
boost::asio::associated_executor_t<Handler>> work_;
};
// The initiating function for the asynchronous operation.
template <typename CompletionToken>
auto async_read_input(const std::string& prompt, CompletionToken&& token)
{
// Define a function object that contains the code to launch the asynchronous
// operation. This is passed the concrete completion handler, followed by any
// additional arguments that were passed through the call to async_initiate.
auto init = [](auto handler, const std::string& prompt)
{
// The body of the initiation function object creates the long-lived state
// and passes it to the C-based API, along with the function pointer.
using state_type = read_input_state<decltype(handler)>;
read_input(prompt.c_str(), &state_type::callback,
state_type::create(std::move(handler)));
};
// The async_initiate function is used to transform the supplied completion
// token to the completion handler. When calling this function we explicitly
// specify the completion signature of the operation. We must also return the
// result of the call since the completion token may produce a return value,
// such as a future.
return boost::asio::async_initiate<CompletionToken, void(std::string)>(
init, // First, pass the function object that launches the operation,
token, // then the completion token that will be transformed to a handler,
prompt); // and, finally, any additional arguments to the function object.
}
//------------------------------------------------------------------------------
void test_callback()
{
boost::asio::io_context io_context;
// Test our asynchronous operation using a lambda as a callback. We will use
// an io_context to obtain an associated executor.
async_read_input("Enter your name",
boost::asio::bind_executor(io_context,
[](const std::string& result)
{
std::cout << "Hello " << result << "\n";
}));
io_context.run();
}
//------------------------------------------------------------------------------
void test_deferred()
{
boost::asio::io_context io_context;
// Test our asynchronous operation using the deferred completion token. This
// token causes the operation's initiating function to package up the
// operation with its arguments to return a function object, which may then be
// used to launch the asynchronous operation.
auto op = async_read_input("Enter your name", boost::asio::deferred);
// Launch our asynchronous operation using a lambda as a callback. We will use
// an io_context to obtain an associated executor.
std::move(op)(
boost::asio::bind_executor(io_context,
[](const std::string& result)
{
std::cout << "Hello " << result << "\n";
}));
io_context.run();
}
//------------------------------------------------------------------------------
void test_future()
{
// Test our asynchronous operation using the use_future completion token.
// This token causes the operation's initiating function to return a future,
// which may be used to synchronously wait for the result of the operation.
std::future<std::string> f =
async_read_input("Enter your name", boost::asio::use_future);
std::string result = f.get();
std::cout << "Hello " << result << "\n";
}
//------------------------------------------------------------------------------
int main()
{
test_callback();
test_deferred();
test_future();
}
| cpp |
asio | data/projects/asio/example/cpp14/operations/composed_4.cpp | //
// composed_4.cpp
// ~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include <boost/asio/bind_executor.hpp>
#include <boost/asio/deferred.hpp>
#include <boost/asio/io_context.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/use_future.hpp>
#include <boost/asio/write.hpp>
#include <cstring>
#include <functional>
#include <iostream>
#include <string>
#include <type_traits>
#include <utility>
using boost::asio::ip::tcp;
// NOTE: This example requires the new boost::asio::async_initiate function. For
// an example that works with the Networking TS style of completion tokens,
// please see an older version of asio.
//------------------------------------------------------------------------------
// In this composed operation we repackage an existing operation, but with a
// different completion handler signature. We will also intercept an empty
// message as an invalid argument, and propagate the corresponding error to the
// user. The asynchronous operation requirements are met by delegating
// responsibility to the underlying operation.
template <typename CompletionToken>
auto async_write_message(tcp::socket& socket,
const char* message, CompletionToken&& token)
// The return type of the initiating function is deduced from the combination
// of:
//
// - the CompletionToken type,
// - the completion handler signature, and
// - the asynchronous operation's initiation function object.
//
// When the completion token is a simple callback, the return type is always
// void. In this example, when the completion token is boost::asio::yield_context
// (used for stackful coroutines) the return type would also be void, as
// there is no non-error argument to the completion handler. When the
// completion token is boost::asio::use_future it would be std::future<void>. When
// the completion token is boost::asio::deferred, the return type differs for each
// asynchronous operation.
//
// In C++14 we can omit the return type as it is automatically deduced from
// the return type of boost::asio::async_initiate.
{
// In addition to determining the mechanism by which an asynchronous
// operation delivers its result, a completion token also determines the time
// when the operation commences. For example, when the completion token is a
// simple callback the operation commences before the initiating function
// returns. However, if the completion token's delivery mechanism uses a
// future, we might instead want to defer initiation of the operation until
// the returned future object is waited upon.
//
// To enable this, when implementing an asynchronous operation we must
// package the initiation step as a function object. The initiation function
// object's call operator is passed the concrete completion handler produced
// by the completion token. This completion handler matches the asynchronous
// operation's completion handler signature, which in this example is:
//
// void(boost::system::error_code error)
//
// The initiation function object also receives any additional arguments
// required to start the operation. (Note: We could have instead passed these
// arguments in the lambda capture set. However, we should prefer to
// propagate them as function call arguments as this allows the completion
// token to optimise how they are passed. For example, a lazy future which
// defers initiation would need to make a decay-copy of the arguments, but
// when using a simple callback the arguments can be trivially forwarded
// straight through.)
auto initiation = [](auto&& completion_handler,
tcp::socket& socket, const char* message)
{
// The post operation has a completion handler signature of:
//
// void()
//
// and the async_write operation has a completion handler signature of:
//
// void(boost::system::error_code error, std::size n)
//
// Both of these operations' completion handler signatures differ from our
// operation's completion handler signature. We will adapt our completion
// handler to these signatures by using std::bind, which drops the
// additional arguments.
//
// However, it is essential to the correctness of our composed operation
// that we preserve the executor of the user-supplied completion handler.
// The std::bind function will not do this for us, so we must do this by
// first obtaining the completion handler's associated executor (defaulting
// to the I/O executor - in this case the executor of the socket - if the
// completion handler does not have its own) ...
auto executor = boost::asio::get_associated_executor(
completion_handler, socket.get_executor());
// ... and then binding this executor to our adapted completion handler
// using the boost::asio::bind_executor function.
std::size_t length = std::strlen(message);
if (length == 0)
{
boost::asio::post(
boost::asio::bind_executor(executor,
std::bind(std::forward<decltype(completion_handler)>(
completion_handler), boost::asio::error::invalid_argument)));
}
else
{
boost::asio::async_write(socket,
boost::asio::buffer(message, length),
boost::asio::bind_executor(executor,
std::bind(std::forward<decltype(completion_handler)>(
completion_handler), std::placeholders::_1)));
}
};
// The boost::asio::async_initiate function takes:
//
// - our initiation function object,
// - the completion token,
// - the completion handler signature, and
// - any additional arguments we need to initiate the operation.
//
// It then asks the completion token to create a completion handler (i.e. a
// callback) with the specified signature, and invoke the initiation function
// object with this completion handler as well as the additional arguments.
// The return value of async_initiate is the result of our operation's
// initiating function.
//
// Note that we wrap non-const reference arguments in std::reference_wrapper
// to prevent incorrect decay-copies of these objects.
return boost::asio::async_initiate<
CompletionToken, void(boost::system::error_code)>(
initiation, token, std::ref(socket), message);
}
//------------------------------------------------------------------------------
void test_callback()
{
boost::asio::io_context io_context;
tcp::acceptor acceptor(io_context, {tcp::v4(), 55555});
tcp::socket socket = acceptor.accept();
// Test our asynchronous operation using a lambda as a callback.
async_write_message(socket, "",
[](const boost::system::error_code& error)
{
if (!error)
{
std::cout << "Message sent\n";
}
else
{
std::cout << "Error: " << error.message() << "\n";
}
});
io_context.run();
}
//------------------------------------------------------------------------------
void test_deferred()
{
boost::asio::io_context io_context;
tcp::acceptor acceptor(io_context, {tcp::v4(), 55555});
tcp::socket socket = acceptor.accept();
// Test our asynchronous operation using the deferred completion token. This
// token causes the operation's initiating function to package up the
// operation with its arguments to return a function object, which may then be
// used to launch the asynchronous operation.
auto op = async_write_message(socket, "", boost::asio::deferred);
// Launch the operation using a lambda as a callback.
std::move(op)(
[](const boost::system::error_code& error)
{
if (!error)
{
std::cout << "Message sent\n";
}
else
{
std::cout << "Error: " << error.message() << "\n";
}
});
io_context.run();
}
//------------------------------------------------------------------------------
void test_future()
{
boost::asio::io_context io_context;
tcp::acceptor acceptor(io_context, {tcp::v4(), 55555});
tcp::socket socket = acceptor.accept();
// Test our asynchronous operation using the use_future completion token.
// This token causes the operation's initiating function to return a future,
// which may be used to synchronously wait for the result of the operation.
std::future<void> f = async_write_message(
socket, "", boost::asio::use_future);
io_context.run();
try
{
// Get the result of the operation.
f.get();
std::cout << "Message sent\n";
}
catch (const std::exception& e)
{
std::cout << "Exception: " << e.what() << "\n";
}
}
//------------------------------------------------------------------------------
int main()
{
test_callback();
test_deferred();
test_future();
}
| cpp |
asio | data/projects/asio/example/cpp14/operations/composed_2.cpp | //
// composed_2.cpp
// ~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include <boost/asio/deferred.hpp>
#include <boost/asio/io_context.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/use_future.hpp>
#include <boost/asio/write.hpp>
#include <cstring>
#include <iostream>
#include <string>
#include <type_traits>
#include <utility>
using boost::asio::ip::tcp;
// NOTE: This example requires the new boost::asio::async_initiate function. For
// an example that works with the Networking TS style of completion tokens,
// please see an older version of asio.
//------------------------------------------------------------------------------
// This next simplest example of a composed asynchronous operation involves
// repackaging multiple operations but choosing to invoke just one of them. All
// of these underlying operations have the same completion signature. The
// asynchronous operation requirements are met by delegating responsibility to
// the underlying operations.
template <typename CompletionToken>
auto async_write_message(tcp::socket& socket,
const char* message, bool allow_partial_write,
CompletionToken&& token)
// The return type of the initiating function is deduced from the combination
// of:
//
// - the CompletionToken type,
// - the completion handler signature, and
// - the asynchronous operation's initiation function object.
//
// When the completion token is a simple callback, the return type is void.
// However, when the completion token is boost::asio::yield_context (used for
// stackful coroutines) the return type would be std::size_t, and when the
// completion token is boost::asio::use_future it would be std::future<std::size_t>.
// When the completion token is boost::asio::deferred, the return type differs for
// each asynchronous operation.
//
// In C++14 we can omit the return type as it is automatically deduced from
// the return type of boost::asio::async_initiate.
{
// In addition to determining the mechanism by which an asynchronous
// operation delivers its result, a completion token also determines the time
// when the operation commences. For example, when the completion token is a
// simple callback the operation commences before the initiating function
// returns. However, if the completion token's delivery mechanism uses a
// future, we might instead want to defer initiation of the operation until
// the returned future object is waited upon.
//
// To enable this, when implementing an asynchronous operation we must
// package the initiation step as a function object. The initiation function
// object's call operator is passed the concrete completion handler produced
// by the completion token. This completion handler matches the asynchronous
// operation's completion handler signature, which in this example is:
//
// void(boost::system::error_code error, std::size_t)
//
// The initiation function object also receives any additional arguments
// required to start the operation. (Note: We could have instead passed these
// arguments in the lambda capture set. However, we should prefer to
// propagate them as function call arguments as this allows the completion
// token to optimise how they are passed. For example, a lazy future which
// defers initiation would need to make a decay-copy of the arguments, but
// when using a simple callback the arguments can be trivially forwarded
// straight through.)
auto initiation = [](auto&& completion_handler, tcp::socket& socket,
const char* message, bool allow_partial_write)
{
if (allow_partial_write)
{
// When delegating to an underlying operation we must take care to
// perfectly forward the completion handler. This ensures that our
// operation works correctly with move-only function objects as
// callbacks.
return socket.async_write_some(
boost::asio::buffer(message, std::strlen(message)),
std::forward<decltype(completion_handler)>(completion_handler));
}
else
{
// As above, we must perfectly forward the completion handler when calling
// the alternate underlying operation.
return boost::asio::async_write(socket,
boost::asio::buffer(message, std::strlen(message)),
std::forward<decltype(completion_handler)>(completion_handler));
}
};
// The boost::asio::async_initiate function takes:
//
// - our initiation function object,
// - the completion token,
// - the completion handler signature, and
// - any additional arguments we need to initiate the operation.
//
// It then asks the completion token to create a completion handler (i.e. a
// callback) with the specified signature, and invoke the initiation function
// object with this completion handler as well as the additional arguments.
// The return value of async_initiate is the result of our operation's
// initiating function.
//
// Note that we wrap non-const reference arguments in std::reference_wrapper
// to prevent incorrect decay-copies of these objects.
return boost::asio::async_initiate<
CompletionToken, void(boost::system::error_code, std::size_t)>(
initiation, token, std::ref(socket), message, allow_partial_write);
}
//------------------------------------------------------------------------------
void test_callback()
{
boost::asio::io_context io_context;
tcp::acceptor acceptor(io_context, {tcp::v4(), 55555});
tcp::socket socket = acceptor.accept();
// Test our asynchronous operation using a lambda as a callback.
async_write_message(socket, "Testing callback\r\n", false,
[](const boost::system::error_code& error, std::size_t n)
{
if (!error)
{
std::cout << n << " bytes transferred\n";
}
else
{
std::cout << "Error: " << error.message() << "\n";
}
});
io_context.run();
}
//------------------------------------------------------------------------------
void test_deferred()
{
boost::asio::io_context io_context;
tcp::acceptor acceptor(io_context, {tcp::v4(), 55555});
tcp::socket socket = acceptor.accept();
// Test our asynchronous operation using the deferred completion token. This
// token causes the operation's initiating function to package up the
// operation with its arguments to return a function object, which may then be
// used to launch the asynchronous operation.
auto op = async_write_message(socket,
"Testing deferred\r\n", false, boost::asio::deferred);
// Launch the operation using a lambda as a callback.
std::move(op)(
[](const boost::system::error_code& error, std::size_t n)
{
if (!error)
{
std::cout << n << " bytes transferred\n";
}
else
{
std::cout << "Error: " << error.message() << "\n";
}
});
io_context.run();
}
//------------------------------------------------------------------------------
void test_future()
{
boost::asio::io_context io_context;
tcp::acceptor acceptor(io_context, {tcp::v4(), 55555});
tcp::socket socket = acceptor.accept();
// Test our asynchronous operation using the use_future completion token.
// This token causes the operation's initiating function to return a future,
// which may be used to synchronously wait for the result of the operation.
std::future<std::size_t> f = async_write_message(
socket, "Testing future\r\n", false, boost::asio::use_future);
io_context.run();
try
{
// Get the result of the operation.
std::size_t n = f.get();
std::cout << n << " bytes transferred\n";
}
catch (const std::exception& e)
{
std::cout << "Error: " << e.what() << "\n";
}
}
//------------------------------------------------------------------------------
int main()
{
test_callback();
test_deferred();
test_future();
}
| cpp |
Subsets and Splits