code stringlengths 1 1.05M | repo_name stringlengths 7 65 | path stringlengths 2 255 | language stringclasses 236 values | license stringclasses 24 values | size int64 1 1.05M |
|---|---|---|---|---|---|
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef oatpp_concurrency_SpinLock_hpp
#define oatpp_concurrency_SpinLock_hpp
#ifndef _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#endif // _CRT_SECURE_NO_WARNINGS
#include <atomic>
namespace oatpp { namespace concurrency {
/**
* SpinLock implementation based on atomic.
* Meets the `Lockable` requirements.
*/
class SpinLock {
protected:
std::atomic<bool> m_atom;
public:
/**
* Constructor.
*/
SpinLock();
/**
* Lock spin-lock
*/
void lock();
/**
* Unlock spin-lock
*/
void unlock();
/**
* Try to lock.
* @return - `true` if the lock was acquired, `false` otherwise.
*/
bool try_lock();
};
}}
#endif /* oatpp_concurrency_SpinLock_hpp */
| vincent-in-black-sesame/oat | src/oatpp/core/concurrency/SpinLock.hpp | C++ | apache-2.0 | 1,706 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#include "Thread.hpp"
#if defined(_GNU_SOURCE)
#include <pthread.h>
#endif
namespace oatpp { namespace concurrency {
v_int32 setThreadAffinityToOneCpu(std::thread::native_handle_type nativeHandle, v_int32 cpuIndex) {
return setThreadAffinityToCpuRange(nativeHandle, cpuIndex, cpuIndex);
}
v_int32 setThreadAffinityToCpuRange(std::thread::native_handle_type nativeHandle, v_int32 firstCpuIndex, v_int32 lastCpuIndex) {
#if defined(_GNU_SOURCE)
// NOTE:
// The below line doesn't compile on Android.
//result = pthread_setaffinity_np(nativeHandle, sizeof(cpu_set_t), &cpuset);
// The below line compiles on Android but has not been tested.
//result = sched_setaffinity(nativeHandle, sizeof(cpu_set_t), &cpuset);
#if !defined(__ANDROID__) && !defined(OATPP_COMPAT_BUILD_NO_SET_AFFINITY)
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
for(v_int32 i = firstCpuIndex; i <= lastCpuIndex; i++) {
CPU_SET(i, &cpuset);
}
v_int32 result = pthread_setaffinity_np(nativeHandle, sizeof(cpu_set_t), &cpuset);
if (result != 0) {
OATPP_LOGD("[oatpp::concurrency::Thread::assignThreadToCpu(...)]", "error code - %d", result);
}
return result;
#else
return -1;
#endif
#else
(void)nativeHandle;
(void)firstCpuIndex;
(void)lastCpuIndex;
return -1;
#endif
}
v_int32 calcHardwareConcurrency() {
#if !defined(OATPP_THREAD_HARDWARE_CONCURRENCY)
v_int32 concurrency = std::thread::hardware_concurrency();
if(concurrency == 0) {
OATPP_LOGD("[oatpp::concurrency:Thread::calcHardwareConcurrency()]", "Warning - failed to get hardware_concurrency. Setting hardware_concurrency=1");
concurrency = 1;
}
return concurrency;
#else
return OATPP_THREAD_HARDWARE_CONCURRENCY;
#endif
}
v_int32 getHardwareConcurrency() {
static v_int32 concurrency = calcHardwareConcurrency();
return concurrency;
}
}}
| vincent-in-black-sesame/oat | src/oatpp/core/concurrency/Thread.cpp | C++ | apache-2.0 | 2,875 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef oatpp_concurrency_Thread_hpp
#define oatpp_concurrency_Thread_hpp
#include "oatpp/core/base/Environment.hpp"
#include <thread>
namespace oatpp { namespace concurrency {
/**
* Set thread affinity to one CPU.
* @param nativeHandle - `std::thread::native_handle_type`.
* @param cpuIndex - index of CPU.
* @return - zero on success. Negative value on failure.
* -1 if platform that runs application does not support this call.
*/
v_int32 setThreadAffinityToOneCpu(std::thread::native_handle_type nativeHandle, v_int32 cpuIndex);
/**
* Set thread affinity [firstCpuIndex..lastCpuIndex].
* @param nativeHandle - `std::thread::native_handle_type`.
* @param firstCpuIndex - from CPU-index.
* @param lastCpuIndex - to CPU-index included.
* @return - zero on success. Negative value on failure.
* -1 if platform that runs application does not support this call.
*/
v_int32 setThreadAffinityToCpuRange(std::thread::native_handle_type nativeHandle, v_int32 firstCpuIndex, v_int32 lastCpuIndex);
/**
* Get hardware concurrency.
* @return - OATPP_THREAD_HARDWARE_CONCURRENCY config value if set <br>
* else return std::thread::hardware_concurrency() <br>
* else return 1. <br>
*/
v_int32 getHardwareConcurrency();
}}
#endif /* concurrency_Thread_hpp */
| vincent-in-black-sesame/oat | src/oatpp/core/concurrency/Thread.hpp | C++ | apache-2.0 | 2,268 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#include "Bundle.hpp"
namespace oatpp { namespace data {
void Bundle::put(const oatpp::String& key, const oatpp::Void& polymorph) {
m_data.insert({key, polymorph});
}
const std::unordered_map<oatpp::String, oatpp::Void>& Bundle::getAll() const {
return m_data;
}
}}
| vincent-in-black-sesame/oat | src/oatpp/core/data/Bundle.cpp | C++ | apache-2.0 | 1,270 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef oatpp_data_Bundle_hpp
#define oatpp_data_Bundle_hpp
#include "oatpp/core/Types.hpp"
namespace oatpp { namespace data {
/**
* Bundle of auxiliary data.
*/
class Bundle {
private:
std::unordered_map<oatpp::String, oatpp::Void> m_data;
public:
/**
* Default constructor.
*/
Bundle() = default;
/**
* Default virtual destructor.
*/
virtual ~Bundle() = default;
/**
* Put data by key.
* @param key
* @param polymorph
*/
void put(const oatpp::String& key, const oatpp::Void& polymorph);
/**
* Get data by key.
* @tparam WrapperType
* @param key
* @return
*/
template<typename WrapperType>
WrapperType get(const oatpp::String& key) const {
auto it = m_data.find(key);
if(it == m_data.end()) {
throw std::runtime_error("[oatpp::data::Bundle::get()]: "
"Error. Data not found for key '" + *key + "'.");
}
if(!WrapperType::Class::getType()->extends(it->second.getValueType())) {
throw std::runtime_error("[oatpp::data::Bundle::get()]: Error. Type mismatch for key '" + *key +
"'. Stored '" +
std::string(it->second.getValueType()->classId.name) +
"' vs requested '" + std::string(WrapperType::Class::getType()->classId.name) + "'.");
}
return it->second.template cast<WrapperType>();
}
/**
* Get map of data stored in the bundle.
* @return
*/
const std::unordered_map<oatpp::String, oatpp::Void>& getAll() const;
};
}}
#endif //oatpp_data_Bundle_hpp
| vincent-in-black-sesame/oat | src/oatpp/core/data/Bundle.hpp | C++ | apache-2.0 | 2,592 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#include "FIFOBuffer.hpp"
#include <mutex>
namespace oatpp { namespace data{ namespace buffer {
FIFOBuffer::FIFOBuffer(void* buffer, v_buff_size bufferSize,
v_buff_size readPosition, v_buff_size writePosition,
bool canRead)
: m_buffer((p_char8)buffer)
, m_bufferSize(bufferSize)
, m_readPosition(readPosition)
, m_writePosition(writePosition)
, m_canRead(canRead)
{}
void FIFOBuffer::setBufferPosition(v_buff_size readPosition, v_buff_size writePosition, bool canRead) {
m_readPosition = readPosition;
m_writePosition = writePosition;
m_canRead = canRead;
}
v_io_size FIFOBuffer::availableToRead() const {
if(!m_canRead) {
return 0;
}
if(m_readPosition < m_writePosition) {
return m_writePosition - m_readPosition;
}
return (m_bufferSize - m_readPosition + m_writePosition);
}
v_io_size FIFOBuffer::availableToWrite() const {
if(m_canRead && m_writePosition == m_readPosition) {
return 0;
}
if(m_writePosition < m_readPosition) {
return m_readPosition - m_writePosition;
}
return (m_bufferSize - m_writePosition + m_readPosition);
}
v_buff_size FIFOBuffer::getBufferSize() const {
return m_bufferSize;
}
v_io_size FIFOBuffer::read(void *data, v_buff_size count) {
if(!m_canRead) {
return IOError::RETRY_READ;
}
if(count == 0) {
return 0;
} else if(count < 0) {
throw std::runtime_error("[oatpp::data::buffer::FIFOBuffer::read(...)]: count < 0");
}
if(m_readPosition < m_writePosition) {
auto size = m_writePosition - m_readPosition;
if(size > count) {
size = count;
}
std::memcpy(data, &m_buffer[m_readPosition], (size_t)size);
m_readPosition += size;
if(m_readPosition == m_writePosition) {
m_canRead = false;
}
return size;
}
auto size = m_bufferSize - m_readPosition;
if(size > count){
std::memcpy(data, &m_buffer[m_readPosition], (size_t)count);
m_readPosition += count;
return count;
}
std::memcpy(data, &m_buffer[m_readPosition], (size_t)size);
auto size2 = m_writePosition;
if(size2 > count - size) {
size2 = count - size;
}
std::memcpy(&((p_char8) data)[size], m_buffer, (size_t)size2);
m_readPosition = size2;
if(m_readPosition == m_writePosition) {
m_canRead = false;
}
return (size + size2);
}
v_io_size FIFOBuffer::peek(void *data, v_buff_size count) {
if(!m_canRead) {
return IOError::RETRY_READ;
}
if(count == 0) {
return 0;
} else if(count < 0) {
throw std::runtime_error("[oatpp::data::buffer::FIFOBuffer::peek(...)]: count < 0");
}
if(m_readPosition < m_writePosition) {
auto size = m_writePosition - m_readPosition;
if(size > count) {
size = count;
}
std::memcpy(data, &m_buffer[m_readPosition], (size_t)size);
return size;
}
auto size = m_bufferSize - m_readPosition;
if(size > count){
std::memcpy(data, &m_buffer[m_readPosition], (size_t)count);
return count;
}
std::memcpy(data, &m_buffer[m_readPosition], (size_t)size);
auto size2 = m_writePosition;
if(size2 > count - size) {
size2 = count - size;
}
std::memcpy(&((p_char8) data)[size], m_buffer, (size_t)size2);
return (size + size2);
}
v_io_size FIFOBuffer::commitReadOffset(v_buff_size count) {
if(!m_canRead) {
return IOError::RETRY_READ;
}
if(count == 0) {
return 0;
} else if(count < 0) {
throw std::runtime_error("[oatpp::data::buffer::FIFOBuffer::commitReadOffset(...)]: count < 0");
}
if(m_readPosition < m_writePosition) {
auto size = m_writePosition - m_readPosition;
if(size > count) {
size = count;
}
m_readPosition += size;
if(m_readPosition == m_writePosition) {
m_canRead = false;
}
return size;
}
auto size = m_bufferSize - m_readPosition;
if(size > count){
m_readPosition += count;
return count;
}
auto size2 = m_writePosition;
if(size2 > count - size) {
size2 = count - size;
}
m_readPosition = size2;
if(m_readPosition == m_writePosition) {
m_canRead = false;
}
return (size + size2);
}
v_io_size FIFOBuffer::write(const void *data, v_buff_size count) {
if(m_canRead && m_writePosition == m_readPosition) {
return IOError::RETRY_WRITE;
}
if(count == 0) {
return 0;
} else if(count < 0) {
throw std::runtime_error("[oatpp::data::buffer::FIFOBuffer::write(...)]: count < 0");
} else {
m_canRead = true;
}
if(m_writePosition < m_readPosition) {
auto size = m_readPosition - m_writePosition;
if(size > count) {
size = count;
}
std::memcpy(&m_buffer[m_writePosition], data, (size_t)size);
m_writePosition += size;
return size;
}
auto size = m_bufferSize - m_writePosition;
if(size > count){
std::memcpy(&m_buffer[m_writePosition], data, (size_t)count);
m_writePosition += count;
return count;
}
std::memcpy(&m_buffer[m_writePosition], data, (size_t)size);
auto size2 = m_readPosition;
if(size2 > count - size) {
size2 = count - size;
}
std::memcpy(m_buffer, &((p_char8) data)[size], (size_t)size2);
m_writePosition = size2;
return (size + size2);
}
v_io_size FIFOBuffer::readAndWriteToStream(data::stream::WriteCallback* stream, v_buff_size count, async::Action& action) {
if(!m_canRead) {
return IOError::RETRY_READ;
}
if(count == 0) {
return 0;
} else if(count < 0) {
throw std::runtime_error("[oatpp::data::buffer::FIFOBuffer::readAndWriteToStream(...)]: count < 0");
}
if(m_readPosition < m_writePosition) {
auto size = m_writePosition - m_readPosition;
if(size > count) {
size = count;
}
auto bytesWritten = stream->write(&m_buffer[m_readPosition], size, action);
if(bytesWritten > 0) {
m_readPosition += bytesWritten;
if (m_readPosition == m_writePosition) {
m_canRead = false;
}
}
return bytesWritten;
}
auto size = m_bufferSize - m_readPosition;
/* DO NOT call stream.write() twice if size > count !!! */
if(size > count){
size = count;
} else if(size == 0) {
auto bytesWritten = stream->write(m_buffer, m_writePosition, action);
if(bytesWritten > 0) {
m_readPosition = bytesWritten;
if (m_readPosition == m_writePosition) {
m_canRead = false;
}
}
return bytesWritten;
}
auto bytesWritten = stream->write(&m_buffer[m_readPosition], size, action);
if(bytesWritten > 0) {
m_readPosition += bytesWritten;
}
return bytesWritten;
}
v_io_size FIFOBuffer::readFromStreamAndWrite(data::stream::ReadCallback* stream, v_buff_size count, async::Action& action) {
if(m_canRead && m_writePosition == m_readPosition) {
return IOError::RETRY_WRITE;
}
if(count == 0) {
return 0;
} else if(count < 0) {
throw std::runtime_error("[oatpp::data::buffer::FIFOBuffer::readFromStreamAndWrite(...)]: count < 0");
}
if(m_writePosition < m_readPosition) {
auto size = m_readPosition - m_writePosition;
if(size > count) {
size = count;
}
auto bytesRead = stream->read(&m_buffer[m_writePosition], size, action);
if(bytesRead > 0) {
m_writePosition += bytesRead;
m_canRead = true;
}
return bytesRead;
}
auto size = m_bufferSize - m_writePosition;
/* DO NOT call stream.read() twice if size > count !!! */
if(size > count){
size = count;
} else if(size == 0) {
auto bytesRead = stream->read(m_buffer, m_readPosition, action);
if(bytesRead > 0) {
m_writePosition = bytesRead;
m_canRead = true;
}
return bytesRead;
}
auto bytesRead = stream->read(&m_buffer[m_writePosition], size, action);
if(bytesRead > 0) {
m_writePosition += bytesRead;
m_canRead = true;
}
return bytesRead;
}
v_io_size FIFOBuffer::flushToStream(data::stream::OutputStream* stream) {
if(!m_canRead) {
return 0;
}
v_io_size result = 0;
if(m_readPosition < m_writePosition) {
result = stream->writeExactSizeDataSimple(&m_buffer[m_readPosition], m_writePosition - m_readPosition);
} else {
result = stream->writeExactSizeDataSimple(&m_buffer[m_readPosition], m_bufferSize - m_readPosition);
result += stream->writeExactSizeDataSimple(m_buffer, m_writePosition);
}
setBufferPosition(0, 0, false);
return result;
}
async::CoroutineStarter FIFOBuffer::flushToStreamAsync(const std::shared_ptr<data::stream::OutputStream>& stream)
{
class FlushCoroutine : public oatpp::async::Coroutine<FlushCoroutine> {
private:
FIFOBuffer* m_fifo;
std::shared_ptr<data::stream::OutputStream> m_stream;
private:
data::buffer::InlineWriteData m_data1;
data::buffer::InlineWriteData m_data2;
public:
FlushCoroutine(FIFOBuffer* fifo, const std::shared_ptr<data::stream::OutputStream>& stream)
: m_fifo(fifo)
, m_stream(stream)
{}
Action act() override {
if(!m_fifo->m_canRead) {
return finish();
}
if(m_fifo->m_readPosition < m_fifo->m_writePosition) {
m_data1.set(&m_fifo->m_buffer[m_fifo->m_readPosition], m_fifo->m_writePosition - m_fifo->m_readPosition);
return yieldTo(&FlushCoroutine::fullFlush);
} else {
m_data1.set(&m_fifo->m_buffer[m_fifo->m_readPosition], m_fifo->m_bufferSize - m_fifo->m_readPosition);
m_data2.set(m_fifo->m_buffer, m_fifo->m_writePosition);
return yieldTo(&FlushCoroutine::partialFlush1);
}
}
Action fullFlush() {
return m_stream->writeExactSizeDataAsyncInline(m_data1, yieldTo(&FlushCoroutine::beforeFinish));
}
Action partialFlush1() {
return m_stream->writeExactSizeDataAsyncInline(m_data1, yieldTo(&FlushCoroutine::partialFlush2));
}
Action partialFlush2() {
return m_stream->writeExactSizeDataAsyncInline(m_data2, yieldTo(&FlushCoroutine::beforeFinish));
}
Action beforeFinish() {
m_fifo->setBufferPosition(0, 0, false);
return finish();
}
};
return FlushCoroutine::start(this, stream);
}
//////////////////////////////////////////////////////////////////////////////////////////
// SynchronizedFIFOBuffer
SynchronizedFIFOBuffer::SynchronizedFIFOBuffer(void* buffer, v_buff_size bufferSize,
v_buff_size readPosition, v_buff_size writePosition,
bool canRead)
: m_fifo(buffer, bufferSize, readPosition, writePosition, canRead)
{}
void SynchronizedFIFOBuffer::setBufferPosition(v_buff_size readPosition, v_buff_size writePosition, bool canRead) {
std::lock_guard<oatpp::concurrency::SpinLock> lock(m_lock);
m_fifo.setBufferPosition(readPosition, writePosition, canRead);
}
v_io_size SynchronizedFIFOBuffer::availableToRead() {
std::lock_guard<oatpp::concurrency::SpinLock> lock(m_lock);
return m_fifo.availableToRead();
}
v_io_size SynchronizedFIFOBuffer::availableToWrite() {
std::lock_guard<oatpp::concurrency::SpinLock> lock(m_lock);
return m_fifo.availableToWrite();
}
v_io_size SynchronizedFIFOBuffer::read(void *data, v_buff_size count) {
std::lock_guard<oatpp::concurrency::SpinLock> lock(m_lock);
return m_fifo.read(data, count);
}
v_io_size SynchronizedFIFOBuffer::write(const void *data, v_buff_size count) {
std::lock_guard<oatpp::concurrency::SpinLock> lock(m_lock);
return m_fifo.write(data, count);
}
}}}
| vincent-in-black-sesame/oat | src/oatpp/core/data/buffer/FIFOBuffer.cpp | C++ | apache-2.0 | 12,416 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef oatpp_data_buffer_FIFOBuffer_hpp
#define oatpp_data_buffer_FIFOBuffer_hpp
#include "oatpp/core/data/stream/Stream.hpp"
#include "oatpp/core/IODefinitions.hpp"
#include "oatpp/core/async/Coroutine.hpp"
#include "oatpp/core/concurrency/SpinLock.hpp"
namespace oatpp { namespace data { namespace buffer {
/**
* FIFO operations over the buffer
* !FIFOBuffer is NOT an IOStream despite having similar APIs!
*/
class FIFOBuffer {
private:
p_char8 m_buffer;
v_buff_size m_bufferSize;
v_buff_size m_readPosition;
v_buff_size m_writePosition;
bool m_canRead;
public:
/**
* Constructor.
* @param buffer - pointer to buffer used for reads/writes.
* @param bufferSize - buffer size.
* @param readPosition - initial read position in buffer.
* @param writePosition - initial write position in buffer.
* @param canRead - flag to resolve ambiguity when readPosition == writePosition. If(readPosition == writePosition && canRead) then
* &l:FIFOBuffer::availableToRead (); returns buffer size, and &l:FIFOBuffer::availableToWrite (); returns 0.
*/
FIFOBuffer(void* buffer, v_buff_size bufferSize,
v_buff_size readPosition = 0, v_buff_size writePosition = 0,
bool canRead = false);
/**
* Set read and write positions in buffer.
* @param readPosition - read position in buffer.
* @param writePosition - write position in buffer.
* @param canRead - flag to resolve ambiguity when readPosition == writePosition. If(readPosition == writePosition && canRead) then
* &l:FIFOBuffer::availableToRead (); returns buffer size, and &l:FIFOBuffer::availableToWrite (); returns 0.
*/
void setBufferPosition(v_buff_size readPosition, v_buff_size writePosition, bool canRead);
/**
* Amount of bytes currently available to read from buffer.
* @return &id:oatpp::v_io_size;.
*/
v_io_size availableToRead() const;
/**
* Amount of buffer space currently available for data writes.
* @return &id:oatpp::v_io_size;.
*/
v_io_size availableToWrite() const;
/**
* Get FIFOBuffer size.
* @return - FIFOBuffer size.
*/
v_buff_size getBufferSize() const;
/**
* read up to count bytes from the buffer to data
* @param data
* @param count
* @return [1..count], IOErrors.
*/
v_io_size read(void *data, v_buff_size count);
/**
* Peek up to count of bytes int he buffer
* @param data
* @param count
* @return [1..count], IOErrors.
*/
v_io_size peek(void *data, v_buff_size count);
/**
* Commit read offset
* @param count
* @return [1..count], IOErrors.
*/
v_io_size commitReadOffset(v_buff_size count);
/**
* write up to count bytes from data to buffer
* @param data
* @param count
* @return [1..count], IOErrors.
*/
v_io_size write(const void *data, v_buff_size count);
/**
* call read and then write bytes read to output stream
* @param stream
* @param count
* @param action
* @return [1..count], IOErrors.
*/
v_io_size readAndWriteToStream(data::stream::WriteCallback* stream, v_buff_size count, async::Action& action);
/**
* call stream.read() and then write bytes read to buffer
* @param stream
* @param count
* @param action
* @return
*/
v_io_size readFromStreamAndWrite(data::stream::ReadCallback* stream, v_buff_size count, async::Action& action);
/**
* flush all availableToRead bytes to stream
* @param stream
* @return
*/
v_io_size flushToStream(data::stream::OutputStream* stream);
/**
* flush all availableToRead bytes to stream in asynchronous manner
* @param stream - &id:data::stream::OutputStream;.
* @return - &id:async::CoroutineStarter;.
*/
async::CoroutineStarter flushToStreamAsync(const std::shared_ptr<data::stream::OutputStream>& stream);
};
/**
* Same as FIFOBuffer + synchronization with SpinLock
*/
class SynchronizedFIFOBuffer {
private:
FIFOBuffer m_fifo;
oatpp::concurrency::SpinLock m_lock;
public:
/**
* Constructor.
* @param buffer - pointer to buffer used for reads/writes.
* @param bufferSize - buffer size.
* @param readPosition - initial read position in buffer.
* @param writePosition - initial write position in buffer.
* @param canRead - flag to resolve ambiguity when readPosition == writePosition. If(readPosition == writePosition && canRead) then
* &l:SynchronizedFIFOBuffer::availableToRead (); returns buffer size, and &l:SynchronizedFIFOBuffer::availableToWrite (); returns 0.
*/
SynchronizedFIFOBuffer(void* buffer, v_buff_size bufferSize,
v_buff_size readPosition = 0, v_buff_size writePosition = 0,
bool canRead = false);
/**
* Set read and write positions in buffer.
* @param readPosition - read position in buffer.
* @param writePosition - write position in buffer.
* @param canRead - flag to resolve ambiguity when readPosition == writePosition. If(readPosition == writePosition && canRead) then
* &l:SynchronizedFIFOBuffer::availableToRead (); returns buffer size, and &l:SynchronizedFIFOBuffer::availableToWrite (); returns 0.
*/
void setBufferPosition(v_buff_size readPosition, v_buff_size writePosition, bool canRead);
/**
* Amount of bytes currently available to read from buffer.
* @return &id:oatpp::v_io_size;.
*/
v_io_size availableToRead();
/**
* Amount of buffer space currently available for data writes.
* @return &id:oatpp::v_io_size;.
*/
v_io_size availableToWrite();
/**
* read up to count bytes from the buffer to data
* @param data
* @param count
* @return [1..count], IOErrors.
*/
v_io_size read(void *data, v_buff_size count);
/**
* write up to count bytes from data to buffer
* @param data
* @param count
* @return [1..count], IOErrors.
*/
v_io_size write(const void *data, v_buff_size count);
/* No implementation of other methods */
/* User should implement his own synchronization for other methods */
};
}}}
#endif /* FIFOBuffer_hpp */
| vincent-in-black-sesame/oat | src/oatpp/core/data/buffer/FIFOBuffer.hpp | C++ | apache-2.0 | 7,051 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#include "IOBuffer.hpp"
namespace oatpp { namespace data { namespace buffer {
const v_buff_size IOBuffer::BUFFER_SIZE = 4096;
IOBuffer::IOBuffer()
: m_entry(new v_char8[BUFFER_SIZE])
{}
std::shared_ptr<IOBuffer> IOBuffer::createShared(){
return std::make_shared<IOBuffer>();
}
IOBuffer::~IOBuffer() {
delete [] m_entry;
}
void* IOBuffer::getData(){
return m_entry;
}
v_buff_size IOBuffer::getSize(){
return BUFFER_SIZE;
}
}}}
| vincent-in-black-sesame/oat | src/oatpp/core/data/buffer/IOBuffer.cpp | C++ | apache-2.0 | 1,442 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef oatpp_data_buffer_IOBuffer_hpp
#define oatpp_data_buffer_IOBuffer_hpp
#include "oatpp/core/base/Countable.hpp"
namespace oatpp { namespace data{ namespace buffer {
/**
* Predefined buffer implementation for I/O operations.
* Allocates buffer bytes using &id:oatpp::base::memory::ThreadDistributedMemoryPool;.
*/
class IOBuffer : public oatpp::base::Countable {
public:
/**
* Buffer size constant.
*/
static const v_buff_size BUFFER_SIZE;
private:
p_char8 m_entry;
public:
/**
* Constructor.
*/
IOBuffer();
public:
/**
* Create shared IOBuffer.
* @return
*/
static std::shared_ptr<IOBuffer> createShared();
/**
* Virtual destructor.
*/
~IOBuffer();
/**
* Get pointer to buffer data.
* @return
*/
void* getData();
/**
* Get buffer size.
* @return - should always return &l:IOBuffer::BUFFER_SIZE;.
*/
v_buff_size getSize();
};
}}}
#endif /* oatpp_data_buffer_IOBuffer_hpp */
| vincent-in-black-sesame/oat | src/oatpp/core/data/buffer/IOBuffer.hpp | C++ | apache-2.0 | 1,964 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#include "Processor.hpp"
namespace oatpp { namespace data{ namespace buffer {
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// InlineReadData
InlineReadData::InlineReadData()
: currBufferPtr(nullptr)
, bytesLeft(0)
{}
InlineReadData::InlineReadData(void* data, v_buff_size size)
: currBufferPtr(data)
, bytesLeft(size)
{}
void InlineReadData::set(void* data, v_buff_size size) {
currBufferPtr = data;
bytesLeft = size;
}
void InlineReadData::inc(v_buff_size amount) {
currBufferPtr = &((p_char8) currBufferPtr)[amount];
bytesLeft -= amount;
}
void InlineReadData::setEof() {
currBufferPtr = &((p_char8) currBufferPtr)[bytesLeft];
bytesLeft = 0;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// InlineWriteData
InlineWriteData::InlineWriteData()
: currBufferPtr(nullptr)
, bytesLeft(0)
{}
InlineWriteData::InlineWriteData(const void* data, v_buff_size size)
: currBufferPtr(data)
, bytesLeft(size)
{}
void InlineWriteData::set(const void* data, v_buff_size size) {
currBufferPtr = data;
bytesLeft = size;
}
void InlineWriteData::inc(v_buff_size amount) {
currBufferPtr = &((p_char8) currBufferPtr)[amount];
bytesLeft -= amount;
}
void InlineWriteData::setEof() {
currBufferPtr = &((p_char8) currBufferPtr)[bytesLeft];
bytesLeft = 0;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ProcessingPipeline
ProcessingPipeline::ProcessingPipeline(const std::vector<base::ObjectHandle<Processor>>& processors)
: m_processors(processors), m_intermediateData(processors.size() - 1)
{
}
v_io_size ProcessingPipeline::suggestInputStreamReadSize() {
return m_processors[0]->suggestInputStreamReadSize();
}
v_int32 ProcessingPipeline::iterate(data::buffer::InlineReadData& dataIn,
data::buffer::InlineReadData& dataOut)
{
if(dataOut.bytesLeft > 0) {
return Error::FLUSH_DATA_OUT;
}
v_int32 i = 0;
v_int32 res = Error::OK;
while(res == Error::OK) {
auto& p = m_processors[i];
data::buffer::InlineReadData* currDataIn = &dataIn;
if(i > 0) {
currDataIn = &m_intermediateData[i - 1];
}
data::buffer::InlineReadData* currDataOut = &dataOut;
if(i < (v_int32) m_intermediateData.size()) {
currDataOut = &m_intermediateData[i];
}
while(res == Error::OK) {
res = p->iterate(*currDataIn, *currDataOut);
}
const v_int32 numOfProcessors = v_int32(m_processors.size());
switch (res) {
case Error::PROVIDE_DATA_IN:
if (i > 0) {
i --;
res = Error::OK;
}
break;
case Error::FLUSH_DATA_OUT:
if (i < numOfProcessors - 1) {
i ++;
res = Error::OK;
}
break;
case Error::FINISHED:
if (i < numOfProcessors - 1) {
i ++;
res = Error::OK;
}
break;
}
}
return res;
}
}}}
| vincent-in-black-sesame/oat | src/oatpp/core/data/buffer/Processor.cpp | C++ | apache-2.0 | 4,103 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef oatpp_data_buffer_Processor_hpp
#define oatpp_data_buffer_Processor_hpp
#include "oatpp/core/IODefinitions.hpp"
#include "oatpp/core/base/ObjectHandle.hpp"
#include <vector>
namespace oatpp { namespace data { namespace buffer {
/**
* Convenience structure for stream Async-Inline read operations.
*/
struct InlineReadData {
/**
* Pointer to current position in the buffer.
*/
void* currBufferPtr;
/**
* Bytes left to read to the buffer.
*/
v_buff_size bytesLeft;
/**
* Default constructor.
*/
InlineReadData();
/**
* Constructor.
* @param data
* @param size
*/
InlineReadData(void* data, v_buff_size size);
/**
* Set `currBufferPtr` and `bytesLeft` values. <br>
* @param data - pointer to buffer to store read data.
* @param size - size in bytes of the buffer.
*/
void set(void* data, v_buff_size size);
/**
* Increase position in the read buffer by `amount` bytes. <br>
* This will increase `currBufferPtr` and descrease `bytesLeft` values.
* @param amount
*/
void inc(v_buff_size amount);
/**
* Same as `inc(bytesLeft).`
*/
void setEof();
};
/**
* Convenience structure for stream Async-Inline write operations.
*/
struct InlineWriteData {
/**
* Pointer to current position in the buffer.
*/
const void* currBufferPtr;
/**
* Bytes left to write from the buffer.
*/
v_buff_size bytesLeft;
/**
* Default constructor.
*/
InlineWriteData();
/**
* Constructor.
* @param data
* @param size
*/
InlineWriteData(const void* data, v_buff_size size);
/**
* Set `currBufferPtr` and `bytesLeft` values. <br>
* @param data - pointer to buffer containing data to be written.
* @param size - size in bytes of the buffer.
*/
void set(const void* data, v_buff_size size);
/**
* Increase position in the write buffer by `amount` bytes. <br>
* This will increase `currBufferPtr` and descrease `bytesLeft` values.
* @param amount
*/
void inc(v_buff_size amount);
/**
* Same as `inc(bytesLeft).`
*/
void setEof();
};
/**
* Buffer processor.
* Note: all processors are considered to be stateful.
*/
class Processor {
public:
/**
* Enum of processing errors.
*/
enum Error : v_int32 {
/**
* No error.
*/
OK = 0,
/**
* Caller must set fields of `dataIn` parameter.
*/
PROVIDE_DATA_IN = 1,
/**
* Caller must read all the data from the `dataOut`.
*/
FLUSH_DATA_OUT = 2,
/**
* Processing is finished.
*/
FINISHED = 3
//*********************************************//
// Other values are processor-specific errors. //
//*********************************************//
};
public:
/**
* Default virtual destructor.
*/
virtual ~Processor() = default;
/**
* If the client is using the input stream to read data and push it to the processor,
* the client MAY ask the processor for a suggested read size.
* @return - suggested read size.
*/
virtual v_io_size suggestInputStreamReadSize() = 0;
/**
* Process data.
* @param dataIn - data provided by client to processor. Input data. &id:data::buffer::InlineReadData;.
* Set `dataIn` buffer pointer to `nullptr` to designate the end of input.
* @param dataOut - data provided to client by processor. Output data. &id:data::buffer::InlineReadData;.
* @return - &l:Processor::Error;.
*/
virtual v_int32 iterate(data::buffer::InlineReadData& dataIn,
data::buffer::InlineReadData& dataOut) = 0;
};
/**
* Pipeline of buffer processors.
*/
class ProcessingPipeline : public Processor {
private:
std::vector<base::ObjectHandle<Processor>> m_processors;
std::vector<data::buffer::InlineReadData> m_intermediateData;
public:
/**
* Constructor.
* @param m_processors - the array of processors defining the pipeline.
*/
ProcessingPipeline(const std::vector<base::ObjectHandle<Processor>>& m_processors);
/**
* If the client is using the input stream to read data and push it to the processor,
* the client MAY ask the processor for a suggested read size.
* @return - suggested read size.
*/
v_io_size suggestInputStreamReadSize() override;
/**
* Process data.
* @param dataIn - data provided by client to processor. Input data. &id:data::buffer::InlineReadData;.
* Set `dataIn` buffer pointer to `nullptr` to designate the end of input.
* @param dataOut - data provided to client by processor. Output data. &id:data::buffer::InlineReadData;.
* @return - &l:Processor::Error;.
*/
v_int32 iterate(data::buffer::InlineReadData& dataIn,
data::buffer::InlineReadData& dataOut) override;
};
}}}
#endif // oatpp_data_buffer_Processor_hpp
| vincent-in-black-sesame/oat | src/oatpp/core/data/buffer/Processor.hpp | C++ | apache-2.0 | 5,805 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#include "ObjectMapper.hpp"
#include "oatpp/core/data/stream/BufferStream.hpp"
namespace oatpp { namespace data { namespace mapping {
ObjectMapper::ObjectMapper(const Info& info)
: m_info(info)
{}
const ObjectMapper::Info& ObjectMapper::getInfo() const {
return m_info;
}
oatpp::String ObjectMapper::writeToString(const type::Void& variant) const {
stream::BufferOutputStream stream;
write(&stream, variant);
return stream.toString();
}
}}} | vincent-in-black-sesame/oat | src/oatpp/core/data/mapping/ObjectMapper.cpp | C++ | apache-2.0 | 1,452 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef oatpp_data_mapping_ObjectMapper_hpp
#define oatpp_data_mapping_ObjectMapper_hpp
#include "type/Object.hpp"
#include "type/Type.hpp"
#include "oatpp/core/data/stream/Stream.hpp"
#include "oatpp/core/parser/Caret.hpp"
#include "oatpp/core/parser/ParsingError.hpp"
namespace oatpp { namespace data { namespace mapping {
/**
* Abstract ObjectMapper class.
*/
class ObjectMapper {
public:
/**
* Metadata for ObjectMapper.
*/
class Info {
public:
/**
* Constructor.
* @param _http_content_type
*/
Info(const char* _http_content_type)
: http_content_type(_http_content_type)
{}
/**
* Value for Content-Type http header when DTO is serialized via specified ObjectMapper.
*/
const char* const http_content_type;
};
private:
Info m_info;
public:
/**
* Constructor.
* @param info - Metadata for ObjectMapper.
*/
ObjectMapper(const Info& info);
/**
* Get ObjectMapper metadata.
* @return - ObjectMapper metadata.
*/
const Info& getInfo() const;
/**
* Serialize object to stream. Implement this method.
* @param stream - &id:oatpp::data::stream::ConsistentOutputStream; to serialize object to.
* @param variant - Object to serialize.
*/
virtual void write(data::stream::ConsistentOutputStream* stream, const type::Void& variant) const = 0;
/**
* Deserialize object. Implement this method.
* @param caret - &id:oatpp::parser::Caret; over serialized buffer.
* @param type - pointer to object type. See &id:oatpp::data::mapping::type::Type;.
* @return - deserialized object wrapped in &id:oatpp::Void;.
*/
virtual mapping::type::Void read(oatpp::parser::Caret& caret, const mapping::type::Type* const type) const = 0;
/**
* Serialize object to String.
* @param variant - Object to serialize.
* @return - serialized object as &id:oatpp::String;.
*/
oatpp::String writeToString(const type::Void& variant) const;
/**
* Deserialize object.
* If nullptr is returned - check caret.getError()
* @tparam Wrapper - ObjectWrapper type.
* @param caret - &id:oatpp::parser::Caret; over serialized buffer.
* @return - deserialized Object.
* @throws - depends on implementation.
*/
template<class Wrapper>
Wrapper readFromCaret(oatpp::parser::Caret& caret) const {
auto type = Wrapper::Class::getType();
return read(caret, type).template cast<Wrapper>();
}
/**
* Deserialize object.
* @tparam Wrapper - ObjectWrapper type.
* @param str - serialized data.
* @return - deserialized Object.
* @throws - &id:oatpp::parser::ParsingError;
* @throws - depends on implementation.
*/
template<class Wrapper>
Wrapper readFromString(const oatpp::String& str) const {
auto type = Wrapper::Class::getType();
oatpp::parser::Caret caret(str);
auto result = read(caret, type).template cast<Wrapper>();
if(!result) {
throw oatpp::parser::ParsingError(caret.getErrorMessage(), caret.getErrorCode(), caret.getPosition());
}
return result;
}
};
}}}
#endif /* oatpp_data_mapping_ObjectMapper_hpp */
| vincent-in-black-sesame/oat | src/oatpp/core/data/mapping/ObjectMapper.hpp | C++ | apache-2.0 | 4,117 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#include "TypeResolver.hpp"
namespace oatpp { namespace data { namespace mapping {
TypeResolver::TypeResolver() {
m_knownClasses.resize(data::mapping::type::ClassId::getClassCount(), false);
addKnownClasses({
data::mapping::type::__class::String::CLASS_ID,
data::mapping::type::__class::Any::CLASS_ID,
data::mapping::type::__class::Int8::CLASS_ID,
data::mapping::type::__class::UInt8::CLASS_ID,
data::mapping::type::__class::Int16::CLASS_ID,
data::mapping::type::__class::UInt16::CLASS_ID,
data::mapping::type::__class::Int32::CLASS_ID,
data::mapping::type::__class::UInt32::CLASS_ID,
data::mapping::type::__class::Int64::CLASS_ID,
data::mapping::type::__class::UInt64::CLASS_ID,
data::mapping::type::__class::Float32::CLASS_ID,
data::mapping::type::__class::Float64::CLASS_ID,
data::mapping::type::__class::Boolean::CLASS_ID,
data::mapping::type::__class::AbstractObject::CLASS_ID,
data::mapping::type::__class::AbstractEnum::CLASS_ID,
data::mapping::type::__class::AbstractVector::CLASS_ID,
data::mapping::type::__class::AbstractList::CLASS_ID,
data::mapping::type::__class::AbstractUnorderedSet::CLASS_ID,
data::mapping::type::__class::AbstractPairList::CLASS_ID,
data::mapping::type::__class::AbstractUnorderedMap::CLASS_ID
});
}
void TypeResolver::setKnownClass(const type::ClassId& classId, bool isKnown) {
const v_uint32 id = classId.id;
if(id >= m_knownClasses.size()) {
m_knownClasses.resize(id + 1, false);
}
m_knownClasses[id] = isKnown;
}
void TypeResolver::addKnownClasses(const std::vector<type::ClassId>& knownClasses) {
for(const type::ClassId& id : knownClasses) {
setKnownClass(id, true);
}
}
bool TypeResolver::isKnownClass(const type::ClassId& classId) const {
const v_uint32 id = classId.id;
if(id < m_knownClasses.size()) {
return m_knownClasses[id];
}
return false;
}
bool TypeResolver::isKnownType(const type::Type* type) const {
if (type != nullptr) {
return isKnownClass(type->classId);
}
return false;
}
void TypeResolver::setEnabledInterpretations(const std::vector<std::string>& interpretations) {
m_enabledInterpretations = interpretations;
}
const std::vector<std::string>& TypeResolver::getEnabledInterpretations() const {
return m_enabledInterpretations;
}
const type::Type* TypeResolver::resolveType(const type::Type* type, Cache& cache) const {
if(type == nullptr) {
return nullptr;
}
if(isKnownClass(type->classId)) {
return type;
}
auto it = cache.types.find(type);
if(it != cache.types.end()) {
return it->second;
}
auto interpretation = type->findInterpretation(m_enabledInterpretations);
if(interpretation) {
auto resolution = resolveType(interpretation->getInterpretationType(), cache);
cache.types[type] = resolution;
return resolution;
}
return nullptr;
}
type::Void TypeResolver::resolveValue(const type::Void& value, Cache& cache) const {
if(value.getValueType() == nullptr) {
return nullptr;
}
if(isKnownClass(value.getValueType()->classId)) {
return value;
}
auto typeIt = cache.values.find(value.getValueType());
if(typeIt != cache.values.end()) {
auto valueIt = typeIt->second.find(value);
if(valueIt != typeIt->second.end()) {
return valueIt->second;
}
}
auto interpretation = value.getValueType()->findInterpretation(m_enabledInterpretations);
if(interpretation) {
auto resolution = resolveValue(interpretation->toInterpretation(value), cache);
cache.values[value.getValueType()].insert({value, resolution});
return resolution;
}
return nullptr;
}
const type::Type* TypeResolver::findPropertyType(const type::Type* baseType,
const std::vector<std::string>& path,
v_uint32 pathPosition,
Cache& cache) const
{
if(isKnownType(baseType)) {
if(pathPosition == path.size()) {
return baseType;
} else if(pathPosition < path.size()) {
if(baseType->classId.id == type::__class::AbstractObject::CLASS_ID.id) {
auto dispatcher = static_cast<const type::__class::AbstractObject::PolymorphicDispatcher*>(baseType->polymorphicDispatcher);
const auto& map = dispatcher->getProperties()->getMap();
auto it = map.find(path[pathPosition]);
if(it != map.end()) {
return findPropertyType(it->second->type, path, pathPosition + 1, cache);
}
}
return nullptr;
}
}
if(pathPosition > path.size()) {
throw std::runtime_error("[oatpp::data::mapping::TypeResolver::findPropertyType()]: Error. Invalid state.");
}
auto resolvedType = resolveType(baseType, cache);
if(resolvedType) {
return findPropertyType(resolvedType, path, pathPosition, cache);
}
return nullptr;
}
type::Void TypeResolver::findPropertyValue(const type::Void& baseObject,
const std::vector<std::string>& path,
v_uint32 pathPosition,
Cache& cache) const
{
auto baseType = baseObject.getValueType();
if(isKnownType(baseType)) {
if(pathPosition == path.size()) {
return baseObject;
} else if(pathPosition < path.size()) {
if(baseType->classId.id == type::__class::AbstractObject::CLASS_ID.id && baseObject) {
auto dispatcher = static_cast<const type::__class::AbstractObject::PolymorphicDispatcher*>(baseType->polymorphicDispatcher);
const auto& map = dispatcher->getProperties()->getMap();
auto it = map.find(path[pathPosition]);
if(it != map.end()) {
auto property = it->second;
return findPropertyValue(property->getAsRef(static_cast<type::BaseObject*>(baseObject.get())), path, pathPosition + 1, cache);
}
}
return nullptr;
}
}
if(pathPosition > path.size()) {
throw std::runtime_error("[oatpp::data::mapping::TypeResolver::findPropertyValue()]: Error. Invalid state.");
}
const auto& resolution = resolveValue(baseObject, cache);
if(resolution.getValueType()->classId.id != type::Void::Class::CLASS_ID.id) {
return findPropertyValue(resolution, path, pathPosition, cache);
}
return nullptr;
}
const type::Type* TypeResolver::resolveObjectPropertyType(const type::Type* objectType,
const std::vector<std::string>& path,
Cache& cache) const
{
return findPropertyType(objectType, path, 0, cache);
}
type::Void TypeResolver::resolveObjectPropertyValue(const type::Void& object,
const std::vector<std::string>& path,
Cache& cache) const
{
return findPropertyValue(object, path, 0, cache);
}
}}}
| vincent-in-black-sesame/oat | src/oatpp/core/data/mapping/TypeResolver.cpp | C++ | apache-2.0 | 8,001 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef oatpp_data_mapping_TypeResolver_hpp
#define oatpp_data_mapping_TypeResolver_hpp
#include "type/Object.hpp"
namespace oatpp { namespace data { namespace mapping {
/**
* Helper class to work with oatpp types.
*/
class TypeResolver {
public:
/**
* Local resolution cache used to reduce number of type interpretation iterations.
*/
struct Cache {
/**
* types map.
*/
std::unordered_map<const type::Type*, const type::Type*> types;
/**
* values by type map.
*/
std::unordered_map<const type::Type*, std::unordered_map<type::Void, type::Void>> values;
};
private:
const type::Type* findPropertyType(const type::Type* baseType,
const std::vector<std::string>& path,
v_uint32 pathPosition,
Cache& cache) const;
type::Void findPropertyValue(const type::Void& baseObject,
const std::vector<std::string>& path,
v_uint32 pathPosition,
Cache& cache) const;
private:
std::vector<bool> m_knownClasses;
std::vector<std::string> m_enabledInterpretations;
public:
/**
* Default constructor.
*/
TypeResolver();
/**
* Virtual destructor.
*/
virtual ~TypeResolver() = default;
/**
* Set if the type class is considered known/unknown
* @param classId
* @param isKnown
*/
void setKnownClass(const type::ClassId& classId, bool isKnown);
/**
* Set all mentioned type classes as known.
* @param knownClasses
*/
void addKnownClasses(const std::vector<type::ClassId>& knownClasses);
/**
* Check if type class is known.
* @param classId
* @return
*/
bool isKnownClass(const type::ClassId& classId) const;
/**
* Check if type is known.
* @param type
* @return
*/
bool isKnownType(const type::Type* type) const;
/**
* Set enabled type interpretations.
* @param interpretations
*/
void setEnabledInterpretations(const std::vector<std::string>& interpretations);
/**
* Get enabled type interpretations.
* @return
*/
const std::vector<std::string>& getEnabledInterpretations() const;
/**
* Resolve unknown type according to enabled interpretations.
* @param type - type to resolve.
* @param cache - local cache.
* @return
*/
const type::Type* resolveType(const type::Type* type, Cache& cache) const;
/**
* Resolve unknown value according to enabled interpretations.
* @param value - value to resolve.
* @param cache - local cache.
* @return
*/
type::Void resolveValue(const type::Void& value, Cache& cache) const;
/**
* Traverse object property tree resolving unknown types according to enabled interpretations.
* @param objectType - base object type.
* @param path - vector of property names.
* @param cache - local cache.
* @return - &id:oatpp::Type;. `nullptr` - if couldn't resolve.
*/
const type::Type* resolveObjectPropertyType(const type::Type* objectType,
const std::vector<std::string>& path,
Cache& cache) const;
/**
* Traverse object property tree resolving unknown value types according to enabled interpretations.
* @param object - base object.
* @param path - vector of property names.
* @param cache - local cache.
* @return - value as &id:oatpp::Void;. The `valueType` will be set to resolved type
* or to `oatpp::Void::Class::getType()` if couldn't resolve.
*/
type::Void resolveObjectPropertyValue(const type::Void& object,
const std::vector<std::string>& path,
Cache& cache) const;
};
}}}
#endif // oatpp_data_mapping_TypeResolver_hpp
| vincent-in-black-sesame/oat | src/oatpp/core/data/mapping/TypeResolver.hpp | C++ | apache-2.0 | 4,874 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#include "Any.hpp"
namespace oatpp { namespace data { namespace mapping { namespace type {
namespace __class {
const ClassId Any::CLASS_ID("Any");
Type* Any::getType() {
static Type type(CLASS_ID);
return &type;
}
}
Any::Any()
: ObjectWrapper(__class::Any::getType())
{}
Any::Any(std::nullptr_t) : Any() {}
Any::Any(const std::shared_ptr<AnyHandle>& handle, const Type* const type)
: ObjectWrapper(handle, __class::Any::getType())
{
// As an ObjectWrapper, Any must have this constructor. It is used in ObjectWrapper.cast<T>(...) method.
// However, unlike other ObjectWrappers Any won't change its valueType.
// Any is always object wrapper above AnyHandler.
(void)type;
}
Any::Any(const Any& other)
: ObjectWrapper(
(other.m_ptr) ? std::make_shared<AnyHandle>(other.m_ptr->ptr, other.m_ptr->type) : nullptr,
__class::Any::getType()
)
{}
Any::Any(Any&& other)
: ObjectWrapper(std::move(other.m_ptr), __class::Any::getType())
{}
const Type* Any::getStoredType() const {
if(m_ptr) {
return m_ptr->type;
}
return nullptr;
}
Void Any::retrieve(const Type* type) const {
if(m_ptr) {
if(!m_ptr->type->extends(type)) {
throw std::runtime_error("[oatpp::data::mapping::type::Any::retrieve()]: Error. The value type doesn't match.");
}
return Void(m_ptr->ptr, type);
}
return nullptr;
}
Any& Any::operator=(std::nullptr_t) {
m_ptr.reset();
return *this;
}
Any& Any::operator=(const Any& other) {
if(other) {
m_ptr = std::make_shared<AnyHandle>(other.m_ptr->ptr, other.m_ptr->type);
} else {
m_ptr.reset();
}
return *this;
}
Any& Any::operator=(Any&& other) {
m_ptr = std::move(other.m_ptr);
return *this;
}
bool Any::operator == (std::nullptr_t) const {
return m_ptr == nullptr || m_ptr->ptr == nullptr;
}
bool Any::operator != (std::nullptr_t) const {
return !operator == (nullptr);
}
bool Any::operator == (const Any& other) const {
if(!m_ptr && !other.m_ptr) return true;
if(!m_ptr || !other.m_ptr) return false;
return m_ptr->ptr.get() == other.m_ptr->ptr.get();
}
bool Any::operator != (const Any& other) const {
return !operator == (other);
}
}}}}
| vincent-in-black-sesame/oat | src/oatpp/core/data/mapping/type/Any.cpp | C++ | apache-2.0 | 3,177 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef oatpp_data_mapping_type_Any_hpp
#define oatpp_data_mapping_type_Any_hpp
#include "./Type.hpp"
#include "oatpp/core/base/Countable.hpp"
namespace oatpp { namespace data { namespace mapping { namespace type {
namespace __class {
/**
* Any class.
*/
class Any {
public:
/**
* Class Id.
*/
static const ClassId CLASS_ID;
static Type *getType();
};
}
class AnyHandle : public base::Countable {
public:
AnyHandle(const std::shared_ptr<void>& objPtr, const Type* const objType)
: ptr(objPtr)
, type(objType)
{}
std::shared_ptr<void> ptr;
const Type* const type;
};
/**
* Any - ObjectWrapper to hold Any oatpp mapping-enabled type.
*/
class Any : public ObjectWrapper<AnyHandle, __class::Any>{
public:
/**
* Default constructor.
*/
Any();
/**
* Nullptr constructor.
*/
Any(std::nullptr_t);
/**
* Copy constructor.
* @param other - other Any.
*/
Any(const Any& other);
/**
* Move constructor.
* @param other
*/
Any(Any&& other);
Any(const std::shared_ptr<AnyHandle>& handle, const Type* const type);
/**
* Constructor.
* @tparam T - Underlying type of ObjectWrapper.
* @tparam C - __class of ObjectWrapper.
* @param polymorph - any ObjectWrapper.
*/
template<class T, class C>
Any(const ObjectWrapper<T, C>& polymorph)
: ObjectWrapper(std::make_shared<AnyHandle>(polymorph.getPtr(), polymorph.getValueType()), __class::Any::getType())
{}
/**
* Store any ObjectWrapper in Any.
* @tparam T
* @tparam C
* @param polymorph - ObjectWrapper. Ex.: `oatpp::String`, `oatpp::List<...>`, etc.
*/
template<class T, class C>
void store(const ObjectWrapper<T, C>& polymorph) {
m_ptr = std::make_shared<AnyHandle>(polymorph.getPtr(), polymorph.getValueType());
}
/**
* Get `Type` of the stored object.
* @return - &id:oatpp::data::mapping::type::Type;.
*/
const Type* getStoredType() const;
/**
* Retrieve stored object of type `type`.
* @param type - &id:oatpp::Type;
* @return - &id:oatpp::Void;.
* @throws - `std::runtime_error` - if stored type and type requested do not match.
*/
Void retrieve(const Type* type) const;
/**
* Retrieve stored object.
* @tparam WrapperType - type of the object to retrieve.
* @return - ObjectWrapper of type - `WrapperType`.
* @throws - `std::runtime_error` - if stored type and type requested (`WrapperType`) do not match.
*/
template<class WrapperType>
WrapperType retrieve() const {
const auto& v = retrieve(WrapperType::Class::getType());
return WrapperType(std::static_pointer_cast<typename WrapperType::ObjectType>(v.getPtr()), WrapperType::Class::getType());
}
Any& operator=(std::nullptr_t);
Any& operator=(const Any& other);
Any& operator=(Any&& other);
template<class T, class C>
Any& operator=(const ObjectWrapper<T, C>& polymorph) {
m_ptr = std::make_shared<AnyHandle>(polymorph.getPtr(), polymorph.getValueType());
return *this;
}
bool operator == (std::nullptr_t) const;
bool operator != (std::nullptr_t) const;
bool operator == (const Any& other) const;
bool operator != (const Any& other) const;
};
}}}}
#endif //oatpp_data_mapping_type_Any_hpp
| vincent-in-black-sesame/oat | src/oatpp/core/data/mapping/type/Any.hpp | C++ | apache-2.0 | 4,257 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef oatpp_data_mapping_type_Collection_hpp
#define oatpp_data_mapping_type_Collection_hpp
#include "./Type.hpp"
#include <unordered_set>
namespace oatpp { namespace data { namespace mapping { namespace type {
namespace __class {
/**
* Abstract Collection. <br>
* Ex.: Vector, List, Set.
*/
class Collection {
public:
/**
* Iterator.
*/
struct Iterator {
/**
* Default virtual destructor.
*/
virtual ~Iterator() = default;
/**
* Get current item.
* @return
*/
virtual type::Void get() = 0;
/**
* Iterate to next item.
*/
virtual void next() = 0;
/**
* Check if iterator finished.
* @return
*/
virtual bool finished() = 0;
};
public:
/**
* Polymorphic Dispatcher
*/
class PolymorphicDispatcher {
public:
/**
* Virtual destructor.
*/
virtual ~PolymorphicDispatcher() = default;
/**
* Create Collection.
* @return
*/
virtual type::Void createObject() const = 0;
/**
* Get type of collection items.
* @return
*/
virtual const type::Type* getItemType() const = 0;
/**
* Get collection size.
* @param object - collection.
* @return - size of the collection (elements count).
*/
virtual v_int64 getCollectionSize(const type::Void& object) const = 0;
/**
* Add item.
* @param object - Collection.
* @param item - Item to add.
*/
virtual void addItem(const type::Void& object, const type::Void& item) const = 0;
/**
* Begin collection iteration.
* @param object - Collection.
* @return
*/
virtual std::unique_ptr<Iterator> beginIteration(const type::Void& object) const = 0;
};
template<class ContainerType, class ItemType>
struct Inserter {
static void insert(ContainerType* c, const ItemType& i) {
c->emplace_back(i);
}
};
};
template<class ContainerType, class ItemType, class Clazz>
class StandardCollection {
public:
struct Iterator : public Collection::Iterator {
typename ContainerType::iterator iterator;
typename ContainerType::iterator end;
type::Void get() override {
return *iterator;
}
void next() override {
std::advance(iterator, 1);
}
bool finished() override {
return iterator == end;
}
};
public:
class PolymorphicDispatcher : public Collection::PolymorphicDispatcher {
public:
type::Void createObject() const override {
return type::Void(std::make_shared<ContainerType>(), Clazz::getType());
}
const type::Type* getItemType() const override {
const type::Type* collectionType = Clazz::getType();
return collectionType->params[0];
}
v_int64 getCollectionSize(const type::Void& object) const override {
ContainerType* collection = static_cast<ContainerType*>(object.get());
return collection->size();
}
void addItem(const type::Void& object, const type::Void& item) const override {
ContainerType* collection = static_cast<ContainerType*>(object.get());
const auto& collectionItem = item.template cast<ItemType>();
Collection::Inserter<ContainerType, ItemType>::insert(collection, collectionItem);
}
std::unique_ptr<Collection::Iterator> beginIteration(const type::Void& object) const override {
ContainerType* collection = static_cast<ContainerType*>(object.get());
auto iterator = new Iterator();
iterator->iterator = collection->begin();
iterator->end = collection->end();
return std::unique_ptr<Collection::Iterator>(iterator);
}
};
};
template<class ItemType>
struct Collection::Inserter<std::unordered_set<ItemType>, ItemType> {
static void insert(std::unordered_set<ItemType>* c, const ItemType& i) {
c->emplace(i);
}
};
}
}}}}
#endif //oatpp_data_mapping_type_Collection_hpp
| vincent-in-black-sesame/oat | src/oatpp/core/data/mapping/type/Collection.hpp | C++ | apache-2.0 | 4,898 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#include "Enum.hpp"
namespace oatpp { namespace data { namespace mapping { namespace type {
namespace __class {
const ClassId AbstractEnum::CLASS_ID("Enum");
}
}}}}
| vincent-in-black-sesame/oat | src/oatpp/core/data/mapping/type/Enum.cpp | C++ | apache-2.0 | 1,166 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef oatpp_data_mapping_type_Enum_hpp
#define oatpp_data_mapping_type_Enum_hpp
#include "./Any.hpp"
#include "./Primitive.hpp"
#include "oatpp/core/data/share/MemoryLabel.hpp"
#include <type_traits>
#include <unordered_map>
#include <vector>
namespace oatpp { namespace data { namespace mapping { namespace type {
/**
* Errors of enum interpretation.
*/
enum class EnumInterpreterError : v_int32 {
/**
* The interpretation was successful.
*/
OK = 0,
/**
* Wrong `Interpreter` is used to interpret the variable. <br>
* This may also occur if for example: <br>
* `oatpp::Enum<T>` is passed to interpreter of `oatpp::Enum<T>::NotNull`.
*/
TYPE_MISMATCH_ENUM = 1,
/**
* Wrong &id:oatpp::data::mapping::type::Primitive; is passed to interpreter.
*/
TYPE_MISMATCH_ENUM_VALUE = 2,
/**
* Interpreter constraint is violated. <br>
* The constraint was set to `NotNull` but interpretation to/from `nullptr` is requested.
*/
CONSTRAINT_NOT_NULL = 3,
/**
* Enum entry not found.
*/
ENTRY_NOT_FOUND = 4,
};
namespace __class {
/**
* Abstract Enum class.
*/
class AbstractEnum {
public:
static const ClassId CLASS_ID;
public:
class PolymorphicDispatcher {
public:
PolymorphicDispatcher(bool pNotNull)
: notNull(pNotNull)
{}
virtual ~PolymorphicDispatcher() = default;
const bool notNull;
virtual type::Void createObject() const = 0;
virtual type::Void toInterpretation(const type::Void& enumValue, EnumInterpreterError& error) const = 0;
virtual type::Void fromInterpretation(const type::Void& interValue, EnumInterpreterError& error) const = 0;
virtual type::Type* getInterpretationType() const = 0;
virtual std::vector<type::Any> getInterpretedEnum() const = 0;
};
};
template<class T, class Interpreter>
class Enum;
}
/**
* Enum value info.
* @tparam T - underlying enum type.
*/
template<typename T>
struct EnumValueInfo {
/**
* Entry value. T - enum type.
*/
const T value;
/**
* Index of the entry.
*/
const v_int32 index;
/**
* Name of the enum entry or name-qualifier, if qualifier was specified. <br>
* &id:oatpp::data::share::StringKeyLabel;.
*/
const data::share::StringKeyLabel name;
/**
* Description of the enum etry. <br>
* &id:oatpp::data::share::StringKeyLabel;.
*/
const data::share::StringKeyLabel description;
};
template<typename T>
struct EnumInfo {
public:
const char* nameQualifier = nullptr;
std::unordered_map<data::share::StringKeyLabel, EnumValueInfo<T>> byName;
std::unordered_map<v_uint64, EnumValueInfo<T>> byValue;
std::vector<EnumValueInfo<T>> byIndex;
};
template<class T, class Interpreter>
class EnumObjectWrapper; // FWD
template<class T>
class EnumMeta {
template<class Type, class Interpreter>
friend class __class::Enum;
template<class Type, class Interpreter>
friend class EnumObjectWrapper;
public:
typedef T EnumType;
protected:
static EnumInfo<T>* getInfo() {
static EnumInfo<T> info;
return &info;
}
};
/**
* Enum interpreter `AsString`
* @tparam T
* @tparam notnull
*/
template<class T, bool notnull>
class EnumInterpreterAsString {
public:
typedef String UnderlyingTypeObjectWrapper;
public:
template <bool N>
using InterpreterType = EnumInterpreterAsString<T, N>;
public:
constexpr static bool notNull = notnull;
public:
static Void toInterpretation(const Void& enumValue, EnumInterpreterError& error);
static Void fromInterpretation(const Void& interValue, EnumInterpreterError& error);
static Type* getInterpretationType();
};
/**
* Enum interpreter `AsNumber`
* @tparam T
* @tparam notnull
*/
template<class T, bool notnull>
class EnumInterpreterAsNumber {
private:
typedef typename std::underlying_type<T>::type EnumUnderlyingType;
public:
typedef typename ObjectWrapperByUnderlyingType<EnumUnderlyingType>::ObjectWrapper UnderlyingTypeObjectWrapper;
public:
template <bool N>
using InterpreterType = EnumInterpreterAsNumber<T, N>;
public:
constexpr static bool notNull = notnull;
public:
static Void toInterpretation(const Void& enumValue, EnumInterpreterError& error);
static Void fromInterpretation(const Void& interValue, EnumInterpreterError& error);
static Type* getInterpretationType();
};
/**
* Template class for `oatpp::Enum<T>`.
* @tparam T - enum type.
* @tparam EnumInterpreter - enum interpreter.
*/
template<class T, class EnumInterpreter>
class EnumObjectWrapper : public ObjectWrapper<T, __class::Enum<T, EnumInterpreter>>{
template<class Type, class Interpreter>
friend class EnumObjectWrapper;
public:
typedef typename std::underlying_type<T>::type UnderlyingEnumType;
typedef T Z__EnumType;
typedef __class::Enum<T, EnumInterpreter> EnumObjectClass;
/**
* Template parameter - `Interpreter`.
*/
typedef EnumInterpreter Interpreter;
public:
/**
* Enum interpreted `AsString`.
*/
typedef EnumObjectWrapper<T, EnumInterpreterAsString<T, EnumInterpreter::notNull>> AsString;
/**
* Enum interpreted `AsNumber`.
*/
typedef EnumObjectWrapper<T, EnumInterpreterAsNumber<T, EnumInterpreter::notNull>> AsNumber;
/**
* Enum with `NotNull` interpretation constraint.
*/
typedef EnumObjectWrapper<T, typename EnumInterpreter::template InterpreterType<true>> NotNull;
public:
EnumObjectWrapper(const std::shared_ptr<T>& ptr, const type::Type* const valueType)
: type::ObjectWrapper<T, EnumObjectClass>(ptr, valueType)
{}
/**
* Default constructor.
*/
EnumObjectWrapper() {}
/**
* Nullptr constructor.
*/
EnumObjectWrapper(std::nullptr_t) {}
/**
* Constructor.
* @param ptr
*/
EnumObjectWrapper(const std::shared_ptr<T>& ptr)
: type::ObjectWrapper<T, EnumObjectClass>(ptr)
{}
/**
* Constructor.
* @param ptr
*/
EnumObjectWrapper(std::shared_ptr<T>&& ptr)
: type::ObjectWrapper<T, EnumObjectClass>(std::forward<std::shared_ptr<T>>(ptr))
{}
/**
* Copy-constructor.
* @tparam OtherInter
* @param other
*/
template<class OtherInter>
EnumObjectWrapper(const EnumObjectWrapper<T, OtherInter>& other)
: type::ObjectWrapper<T, EnumObjectClass>(other.m_ptr)
{}
/**
* Move-constructor.
* @tparam OtherInter
* @param other
*/
template<class OtherInter>
EnumObjectWrapper(EnumObjectWrapper<T, OtherInter>&& other)
: type::ObjectWrapper<T, EnumObjectClass>(std::move(other.m_ptr))
{}
inline EnumObjectWrapper& operator = (std::nullptr_t) {
this->m_ptr.reset();
return *this;
}
template<class OtherInter>
inline EnumObjectWrapper& operator = (const EnumObjectWrapper<T, OtherInter>& other) {
this->m_ptr = other.m_ptr;
return *this;
}
template<class OtherInter>
inline EnumObjectWrapper& operator = (EnumObjectWrapper<T, OtherInter>&& other) {
this->m_ptr = std::move(other.m_ptr);
return *this;
}
public:
/**
* Constructor by value.
* @param value
*/
EnumObjectWrapper(T value)
: type::ObjectWrapper<T, EnumObjectClass>(std::make_shared<T>(value))
{}
EnumObjectWrapper& operator = (T value) {
this->m_ptr = std::make_shared<T>(value);
return *this;
}
T operator*() const {
return this->m_ptr.operator*();
}
template<typename TP,
typename enabled = typename std::enable_if<std::is_same<TP, std::nullptr_t>::value, void>::type
>
inline bool operator == (TP){
return this->m_ptr.get() == nullptr;
}
template<typename TP,
typename enabled = typename std::enable_if<std::is_same<TP, std::nullptr_t>::value, void>::type
>
inline bool operator != (TP){
return this->m_ptr.get() != nullptr;
}
template<typename TP,
typename enabled = typename std::enable_if<std::is_same<TP, T>::value, void>::type
>
inline bool operator == (TP value) const {
if(!this->m_ptr) return false;
return *this->m_ptr == value;
}
template<typename TP,
typename enabled = typename std::enable_if<std::is_same<TP, T>::value, void>::type
>
inline bool operator != (TP value) const {
if(!this->m_ptr) return true;
return *this->m_ptr != value;
}
template<typename TP,
typename enabled = typename std::enable_if<std::is_same<typename TP::Z__EnumType, Z__EnumType>::value, void>::type
>
inline bool operator == (const TP &other) const {
if(this->m_ptr.get() == other.m_ptr.get()) return true;
if(!this->m_ptr || !other.m_ptr) return false;
return *this->m_ptr == *other.m_ptr;
}
template<typename TP,
typename enabled = typename std::enable_if<std::is_same<typename TP::Z__EnumType, Z__EnumType>::value, void>::type
>
inline bool operator != (const TP &other) const {
return !operator == (other);
}
template<typename TP,
typename enabled = typename std::enable_if<std::is_same<TP, T>::value, void>::type
>
inline operator TP() const {
return *this->m_ptr;
}
public:
/**
* Get &l:EnumValueInfo <T>; by name.
* @param name - name or name-qualifier of the enum entry.
* @return - &l:EnumValueInfo <T>;.
* @throws - `std::runtime_error` if not found.
*/
static const EnumValueInfo<T>& getEntryByName(const String& name) {
auto it = EnumMeta<T>::getInfo()->byName.find(name);
if(it != EnumMeta<T>::getInfo()->byName.end()) {
return it->second;
}
throw std::runtime_error("[oatpp::data::mapping::type::Enum::getEntryByName()]: Error. Entry not found.");
}
/**
* Get &l:EnumValueInfo <T>; by enum value.
* @param value - enum value.
* @return - &l:EnumValueInfo <T>;.
* @throws - `std::runtime_error` if not found.
*/
static const EnumValueInfo<T>& getEntryByValue(T value) {
auto it = EnumMeta<T>::getInfo()->byValue.find(static_cast<v_uint64>(value));
if(it != EnumMeta<T>::getInfo()->byValue.end()) {
return it->second;
}
throw std::runtime_error("[oatpp::data::mapping::type::Enum::getEntryByValue()]: Error. Entry not found.");
}
/**
* Get &l:EnumValueInfo <T>; by integer value.
* @param value - integer value.
* @return - &l:EnumValueInfo <T>;.
* @throws - `std::runtime_error` if not found.
*/
static const EnumValueInfo<T>& getEntryByUnderlyingValue(UnderlyingEnumType value) {
auto it = EnumMeta<T>::getInfo()->byValue.find(static_cast<v_uint64>(value));
if(it != EnumMeta<T>::getInfo()->byValue.end()) {
return it->second;
}
throw std::runtime_error("[oatpp::data::mapping::type::Enum::getEntryByUnderlyingValue()]: Error. Entry not found.");
}
/**
* Get &l:EnumValueInfo <T>; by index.
* @param index - index of the entry in the enum.
* @return - &l:EnumValueInfo <T>;.
* @throws - `std::runtime_error` if not found.
*/
static const EnumValueInfo<T>& getEntryByIndex(v_int32 index) {
if(index >= 0 && index < EnumMeta<T>::getInfo()->byIndex.size()) {
return EnumMeta<T>::getInfo()->byIndex[index];
}
throw std::runtime_error("[oatpp::data::mapping::type::Enum::getEntryByIndex()]: Error. Entry not found.");
}
/**
* Get `std::vector` of &l:EnumValueInfo <T>;.
* @return - `std::vector` of &l:EnumValueInfo <T>;.
*/
static const std::vector<EnumValueInfo<T>>& getEntries() {
return EnumMeta<T>::getInfo()->byIndex;
}
};
/**
* Mapping-enabled Enum. See &l:EnumObjectWrapper;.
*/
template <class T>
using Enum = EnumObjectWrapper<T, EnumInterpreterAsString<T, false>>;
template<class T, bool notnull>
Void EnumInterpreterAsString<T, notnull>::toInterpretation(const Void& enumValue, EnumInterpreterError& error) {
typedef EnumObjectWrapper<T, EnumInterpreterAsString<T, notnull>> EnumOW;
if(enumValue.getValueType() != EnumOW::Class::getType()) {
error = EnumInterpreterError::TYPE_MISMATCH_ENUM;
return Void(nullptr, String::Class::getType());
}
if(!enumValue) {
if(notnull) {
error = EnumInterpreterError::CONSTRAINT_NOT_NULL;
return Void(nullptr, String::Class::getType());
}
return Void(nullptr, String::Class::getType());
}
const auto& ow = enumValue.template cast<EnumOW>();
const auto& entry = EnumOW::getEntryByValue(*ow);
return entry.name.toString();
}
template<class T, bool notnull>
Void EnumInterpreterAsString<T, notnull>::fromInterpretation(const Void& interValue, EnumInterpreterError& error) {
typedef EnumObjectWrapper<T, EnumInterpreterAsString<T, notnull>> EnumOW;
if(interValue.getValueType() != String::Class::getType()) {
error = EnumInterpreterError::TYPE_MISMATCH_ENUM_VALUE;
return Void(nullptr, EnumOW::Class::getType());
}
if(!interValue) {
if(notnull) {
error = EnumInterpreterError::CONSTRAINT_NOT_NULL;
return Void(nullptr, EnumOW::Class::getType());
}
return Void(nullptr, EnumOW::Class::getType());
}
try {
const auto &entry = EnumOW::getEntryByName(interValue.template cast<String>());
return EnumOW(entry.value);
} catch (const std::runtime_error&) { // TODO - add a specific error for this.
error = EnumInterpreterError::ENTRY_NOT_FOUND;
}
return Void(nullptr, EnumOW::Class::getType());
}
template<class T, bool notnull>
Type* EnumInterpreterAsString<T, notnull>::getInterpretationType() {
return String::Class::getType();
}
template<class T, bool notnull>
Void EnumInterpreterAsNumber<T, notnull>::toInterpretation(const Void& enumValue, EnumInterpreterError& error) {
typedef EnumObjectWrapper<T, EnumInterpreterAsNumber<T, notnull>> EnumOW;
typedef typename std::underlying_type<T>::type EnumUT;
typedef typename ObjectWrapperByUnderlyingType<EnumUT>::ObjectWrapper UTOW;
if(enumValue.getValueType() != EnumOW::Class::getType()) {
error = EnumInterpreterError::TYPE_MISMATCH_ENUM;
return Void(nullptr, UTOW::Class::getType());
}
if(!enumValue) {
if(notnull) {
error = EnumInterpreterError::CONSTRAINT_NOT_NULL;
return Void(nullptr, UTOW::Class::getType());
}
return Void(nullptr, UTOW::Class::getType());
}
const auto& ow = enumValue.template cast<EnumOW>();
return UTOW(static_cast<EnumUT>(*ow));
}
template<class T, bool notnull>
Void EnumInterpreterAsNumber<T, notnull>::fromInterpretation(const Void& interValue, EnumInterpreterError& error) {
typedef EnumObjectWrapper<T, EnumInterpreterAsNumber<T, notnull>> EnumOW;
typedef typename std::underlying_type<T>::type EnumUT;
typedef typename ObjectWrapperByUnderlyingType<EnumUT>::ObjectWrapper OW;
if(interValue.getValueType() != OW::Class::getType()) {
error = EnumInterpreterError::TYPE_MISMATCH_ENUM_VALUE;
return Void(nullptr, EnumOW::Class::getType());
}
if(!interValue) {
if(notnull) {
error = EnumInterpreterError::CONSTRAINT_NOT_NULL;
return Void(nullptr, EnumOW::Class::getType());
}
return Void(nullptr, EnumOW::Class::getType());
}
try{
const auto& entry = EnumOW::getEntryByUnderlyingValue(
interValue.template cast<OW>()
);
return EnumOW(entry.value);
} catch (const std::runtime_error&) { // TODO - add a specific error for this.
error = EnumInterpreterError::ENTRY_NOT_FOUND;
}
return Void(nullptr, EnumOW::Class::getType());
}
template<class T, bool notnull>
Type* EnumInterpreterAsNumber<T, notnull>::getInterpretationType() {
typedef typename std::underlying_type<T>::type EnumUT;
return ObjectWrapperByUnderlyingType<EnumUT>::ObjectWrapper::Class::getType();
}
namespace __class {
template<class T, class Interpreter>
class Enum : public AbstractEnum {
private:
class PolymorphicDispatcher : public AbstractEnum::PolymorphicDispatcher {
public:
PolymorphicDispatcher()
: AbstractEnum::PolymorphicDispatcher(Interpreter::notNull)
{}
type::Void createObject() const override {
return type::Void(std::make_shared<T>(), getType());
}
type::Void toInterpretation(const type::Void& enumValue, EnumInterpreterError& error) const override {
return Interpreter::toInterpretation(enumValue, error);
}
type::Void fromInterpretation(const type::Void& interValue, EnumInterpreterError& error) const override {
return Interpreter::fromInterpretation(interValue, error);
}
type::Type* getInterpretationType() const override {
return Interpreter::getInterpretationType();
}
std::vector<type::Any> getInterpretedEnum() const override {
typedef type::EnumObjectWrapper<T, Interpreter> EnumOW;
std::vector<type::Any> result({});
for(const auto& e : EnumOW::getEntries()) {
type::EnumInterpreterError error = type::EnumInterpreterError::OK;
result.push_back(type::Any(toInterpretation(EnumOW(e.value), error)));
if(error != type::EnumInterpreterError::OK) {
throw std::runtime_error("[oatpp::data::mapping::type::__class::Enum<T, Interpreter>::getInterpretedEnum()]: Unknown error.");
}
}
return result;
}
};
private:
static Type createType() {
Type::Info info;
info.nameQualifier = type::EnumMeta<T>::getInfo()->nameQualifier;
info.polymorphicDispatcher = new PolymorphicDispatcher();
return Type(__class::AbstractEnum::CLASS_ID, info);
}
public:
static Type* getType() {
static Type type = createType();
return &type;
}
};
}
}}}}
namespace std {
template<class T, class I>
struct hash <oatpp::data::mapping::type::EnumObjectWrapper<T, I>> {
typedef oatpp::data::mapping::type::EnumObjectWrapper<T, I> argument_type;
typedef v_uint64 result_type;
result_type operator()(argument_type const &e) const noexcept {
if (e.get() == nullptr) return 0;
return static_cast<v_uint64>(*e);
}
};
}
#endif // oatpp_data_mapping_type_Enum_hpp
| vincent-in-black-sesame/oat | src/oatpp/core/data/mapping/type/Enum.hpp | C++ | apache-2.0 | 18,833 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#include "./List.hpp"
namespace oatpp { namespace data { namespace mapping { namespace type {
namespace __class {
const ClassId AbstractList::CLASS_ID("List");
}
}}}}
| vincent-in-black-sesame/oat | src/oatpp/core/data/mapping/type/List.cpp | C++ | apache-2.0 | 1,172 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef oatpp_data_mapping_type_List_hpp
#define oatpp_data_mapping_type_List_hpp
#include "./Collection.hpp"
#include "./Type.hpp"
#include <list>
#include <initializer_list>
namespace oatpp { namespace data { namespace mapping { namespace type {
namespace __class {
/**
* Abstract list class.
*/
class AbstractList {
public:
/**
* Class Id.
*/
static const ClassId CLASS_ID;
};
template<class T>
class List;
}
/**
* `ObjectWrapper` over `std::list<T>`
* @tparam T - Item `ObjectWrapper` type.
* @tparam C - Class.
*/
template<class T, class C>
class ListObjectWrapper : public type::ObjectWrapper<std::list<T>, C> {
public:
typedef std::list<T> TemplateObjectType;
typedef C TemplateObjectClass;
public:
OATPP_DEFINE_OBJECT_WRAPPER_DEFAULTS(ListObjectWrapper, TemplateObjectType, TemplateObjectClass)
ListObjectWrapper(std::initializer_list<T> ilist)
: type::ObjectWrapper<TemplateObjectType, TemplateObjectClass>(std::make_shared<TemplateObjectType>(ilist))
{}
static ListObjectWrapper createShared() {
return std::make_shared<TemplateObjectType>();
}
ListObjectWrapper& operator = (std::initializer_list<T> ilist) {
this->m_ptr = std::make_shared<TemplateObjectType>(ilist);
return *this;
}
T& operator[] (v_buff_usize index) const {
auto it = this->m_ptr->begin();
std::advance(it, index);
return *it;
}
TemplateObjectType& operator*() const {
return this->m_ptr.operator*();
}
};
/**
* Mapping-Enabled List. See - &l:ListObjectWrapper;.
*/
template<class T>
using List = ListObjectWrapper<T, __class::List<T>>;
typedef List<Void> AbstractList;
namespace __class {
template<class T>
class List : public AbstractList {
private:
static Type createType() {
Type::Info info;
info.params.push_back(T::Class::getType());
info.polymorphicDispatcher = new typename StandardCollection<std::list<T>, T, List>::PolymorphicDispatcher();
info.isCollection = true;
return Type(__class::AbstractList::CLASS_ID, info);
}
public:
static Type* getType() {
static Type type = createType();
return &type;
}
};
}
}}}}
#endif // oatpp_data_mapping_type_List_hpp
| vincent-in-black-sesame/oat | src/oatpp/core/data/mapping/type/List.hpp | C++ | apache-2.0 | 3,237 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef oatpp_data_mapping_type_Map_hpp
#define oatpp_data_mapping_type_Map_hpp
#include "./Type.hpp"
#include <list>
namespace oatpp { namespace data { namespace mapping { namespace type {
namespace __class {
/**
* Abstract Map. <br>
* Ex.: UnorderedMap, Fields.
*/
class Map {
public:
/**
* Iterator.
*/
struct Iterator {
/**
* Default virtual destructor.
*/
virtual ~Iterator() = default;
/**
* Get current item key.
* @return
*/
virtual type::Void getKey() = 0;
/**
* Get current item value.
* @return
*/
virtual type::Void getValue() = 0;
/**
* Iterate to next item.
*/
virtual void next() = 0;
/**
* Check if iterator finished.
* @return
*/
virtual bool finished() = 0;
};
public:
/**
* Polymorphic Dispatcher
*/
class PolymorphicDispatcher {
public:
/**
* Virtual destructor.
*/
virtual ~PolymorphicDispatcher() = default;
/**
* Create Map.
* @return
*/
virtual type::Void createObject() const = 0;
/**
* Get type of map keys.
* @return
*/
virtual const type::Type* getKeyType() const = 0;
/**
* Get type of map values.
* @return
*/
virtual const type::Type* getValueType() const = 0;
/**
* Get map size.
* @param object - map object.
* @return - size of the map.
*/
virtual v_int64 getMapSize(const type::Void& object) const = 0;
/**
* Add item.
* @param object - Map.
* @param key
* @param value
*/
virtual void addItem(const type::Void& object, const type::Void& key, const type::Void& value) const = 0;
/**
* Begin map iteration.
* @param object - Map.
* @return
*/
virtual std::unique_ptr<Iterator> beginIteration(const type::Void& object) const = 0;
};
template<class ContainerType, class KeyType, class ValueType>
struct Inserter {
static void insert(ContainerType* c, const KeyType& k, const ValueType& v) {
(*c)[k] = v;
}
};
};
template<class ContainerType, class KeyType, class ValueType, class Clazz>
class StandardMap {
public:
struct Iterator : public Map::Iterator {
typename ContainerType::iterator iterator;
typename ContainerType::iterator end;
type::Void getKey() override {
return iterator->first;
}
type::Void getValue() override {
return iterator->second;
}
void next() override {
std::advance(iterator, 1);
}
bool finished() override {
return iterator == end;
}
};
public:
class PolymorphicDispatcher : public Map::PolymorphicDispatcher {
public:
type::Void createObject() const override {
return type::Void(std::make_shared<ContainerType>(), Clazz::getType());
}
const type::Type* getKeyType() const override {
const type::Type* mapType = Clazz::getType();
return mapType->params[0];
}
const type::Type* getValueType() const override {
const type::Type* mapType = Clazz::getType();
return mapType->params[1];
}
v_int64 getMapSize(const type::Void& object) const override {
ContainerType* map = static_cast<ContainerType*>(object.get());
return map->size();
}
void addItem(const type::Void& object, const type::Void& key, const type::Void& value) const override {
ContainerType* map = static_cast<ContainerType*>(object.get());
const auto& mapKey = key.template cast<KeyType>();
const auto& mapValue = value.template cast<ValueType>();
Map::Inserter<ContainerType, KeyType, ValueType>::insert(map, mapKey, mapValue);
}
std::unique_ptr<Map::Iterator> beginIteration(const type::Void& object) const override {
ContainerType* map = static_cast<ContainerType*>(object.get());
auto iterator = new Iterator();
iterator->iterator = map->begin();
iterator->end = map->end();
return std::unique_ptr<Map::Iterator>(iterator);
}
};
};
template<class KeyType, class ValueType>
struct Map::Inserter<std::list<std::pair<KeyType, ValueType>>, KeyType, ValueType> {
static void insert(std::list<std::pair<KeyType, ValueType>>* c, const KeyType& k, const ValueType& v) {
c->push_back({k, v});
}
};
}
}}}}
#endif //oatpp_data_mapping_type_Map_hpp
| vincent-in-black-sesame/oat | src/oatpp/core/data/mapping/type/Map.hpp | C++ | apache-2.0 | 5,357 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#include "./Object.hpp"
namespace oatpp { namespace data { namespace mapping { namespace type {
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// BaseObject
void BaseObject::set(v_int64 offset, const Void& value) {
Void* property = (Void*)(((v_int64) m_basePointer) + offset);
*property = value;
}
Void BaseObject::get(v_int64 offset) const {
Void* property = (Void*)(((v_int64) m_basePointer) + offset);
return *property;
}
Void& BaseObject::getAsRef(v_int64 offset) const {
Void* property = (Void*)(((v_int64) m_basePointer) + offset);
return *property;
}
void BaseObject::setBasePointer(void* basePointer) {
m_basePointer = basePointer;
}
void* BaseObject::getBasePointer() const {
return m_basePointer;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// BaseObject::Properties
BaseObject::Property* BaseObject::Properties::pushBack(Property* property) {
m_map.insert({property->name, property});
m_list.push_back(property);
return property;
}
void BaseObject::Properties::pushFrontAll(Properties* properties) {
m_map.insert(properties->m_map.begin(), properties->m_map.end());
m_list.insert(m_list.begin(), properties->m_list.begin(), properties->m_list.end());
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// BaseObject::Property
BaseObject::Property::Property(v_int64 pOffset, const char* pName, const Type* pType)
: offset(pOffset)
, name(pName)
, type(pType)
{}
void BaseObject::Property::set(BaseObject* object, const Void& value) {
object->set(offset, value);
}
Void BaseObject::Property::get(BaseObject* object) {
return object->get(offset);
}
Void& BaseObject::Property::getAsRef(BaseObject* object) {
return object->getAsRef(offset);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Object
namespace __class {
const ClassId AbstractObject::CLASS_ID("Object");
}
const mapping::type::Type* DTO::getParentType() {
return nullptr;
}
const char* DTO::Z__CLASS_TYPE_NAME() {
return "DTO";
}
oatpp::data::mapping::type::BaseObject::Properties* DTO::Z__CLASS_GET_FIELDS_MAP() {
static data::mapping::type::BaseObject::Properties map;
return ↦
}
BaseObject::Properties* DTO::Z__CLASS_EXTEND(BaseObject::Properties* properties, BaseObject::Properties* extensionProperties) {
properties->pushFrontAll(extensionProperties);
return properties;
}
}}}}
| vincent-in-black-sesame/oat | src/oatpp/core/data/mapping/type/Object.cpp | C++ | apache-2.0 | 3,635 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef oatpp_data_type_Object_hpp
#define oatpp_data_type_Object_hpp
#include "./Type.hpp"
#include "./Any.hpp"
#include "./Primitive.hpp"
#include "./Enum.hpp"
#include "./UnorderedMap.hpp"
#include "./PairList.hpp"
#include "./List.hpp"
#include "./Vector.hpp"
#include "./UnorderedSet.hpp"
#include "oatpp/core/base/Countable.hpp"
#include <type_traits>
namespace oatpp { namespace data { namespace mapping { namespace type {
/**
* Base class of all object-like mapping-enabled structures ex.: oatpp::DTO.
*/
class BaseObject : public oatpp::base::Countable {
public:
/**
* Class to map object properties.
*/
class Property {
public:
/**
* Property Type Selector.
*/
class TypeSelector {
public:
/**
* Default destructor.
*/
virtual ~TypeSelector() = default;
/**
* Select property type.
* @param self - pointer to `this` object.
* @return - &id:oatpp::Type;.
*/
virtual const type::Type* selectType(BaseObject* self) = 0;
};
template<class DTOType>
class FieldTypeSelector : public TypeSelector {
public:
const type::Type* selectType(BaseObject* self) override {
return selectFieldType(static_cast<DTOType*>(self));
}
virtual const type::Type* selectFieldType(DTOType* self) = 0;
};
public:
/**
* Editional Info about Property.
*/
struct Info {
/**
* Description.
*/
std::string description = "";
/**
* Pattern.
*/
std::string pattern = "";
/**
* Required.
*/
bool required = false;
/**
* Type selector.
* &l:Property::TypeSelector;.
*/
TypeSelector* typeSelector = nullptr;
};
private:
const v_int64 offset;
public:
/**
* Constructor.
* @param pOffset - memory offset of object field from object start address.
* @param pName - name of the property.
* @param pType - &l:Type; of the property.
*/
Property(v_int64 pOffset, const char* pName, const Type* pType);
/**
* Property name.
*/
const char* const name;
/**
* Property type.
*/
const Type* const type;
/**
* Property additional info.
*/
Info info;
/**
* Set value of object field mapped by this property.
* @param object - object address.
* @param value - value to set.
*/
void set(BaseObject* object, const Void& value);
/**
* Get value of object field mapped by this property.
* @param object - object address.
* @return - value of the field.
*/
Void get(BaseObject* object);
/**
* Get reference to ObjectWrapper of the object field.
* @param object - object address.
* @return - reference to ObjectWrapper of the object field.
*/
Void& getAsRef(BaseObject* object);
};
/**
* Object type properties table.
*/
class Properties {
private:
std::unordered_map<std::string, Property*> m_map;
std::list<Property*> m_list;
public:
/**
* Add property to the end of the list.
* @param property
*/
Property* pushBack(Property* property);
/**
* Add all properties to the beginning of the list.
* @param properties
*/
void pushFrontAll(Properties* properties);
/**
* Get properties as unordered map for random access.
* @return reference to std::unordered_map of std::string to &id:oatpp::data::mapping::type::BaseObject::Property;*.
*/
const std::unordered_map<std::string, Property*>& getMap() const {
return m_map;
}
/**
* Get properties in ordered way.
* @return std::list of &id:oatpp::data::mapping::type::BaseObject::Property;*.
*/
const std::list<Property*>& getList() const {
return m_list;
}
};
private:
void* m_basePointer = this;
private:
void set(v_int64 offset, const Void& value);
Void get(v_int64 offset) const;
Void& getAsRef(v_int64 offset) const;
protected:
void setBasePointer(void* basePointer);
void* getBasePointer() const;
};
namespace __class {
/**
* AbstractObject class.
*/
class AbstractObject {
public:
class PolymorphicDispatcher {
public:
virtual ~PolymorphicDispatcher() = default;
virtual type::Void createObject() const = 0;
virtual const type::BaseObject::Properties* getProperties() const = 0;
};
public:
/**
* Class id.
*/
static const ClassId CLASS_ID;
};
/**
* Template for Object class of type T.
* @tparam T - object type.
*/
template<class T>
class Object : public AbstractObject {
public:
class PolymorphicDispatcher : public AbstractObject::PolymorphicDispatcher {
public:
type::Void createObject() const override {
return type::Void(std::make_shared<T>(), getType());
}
const type::BaseObject::Properties* getProperties() const override {
return propertiesGetter();
}
};
private:
static type::BaseObject::Properties* initProperties() {
/* initializer */
T obj;
/* init parent properties */
auto parentType = Object<typename T::Z__CLASS_EXTENDED>::getType();
if(parentType->parent != nullptr) {
auto dispatcher = static_cast<const AbstractObject::PolymorphicDispatcher*>(parentType->polymorphicDispatcher);
dispatcher->getProperties();
}
/* extend parent properties */
T::Z__CLASS_EXTEND(T::Z__CLASS::Z__CLASS_GET_FIELDS_MAP(), T::Z__CLASS_EXTENDED::Z__CLASS_GET_FIELDS_MAP());
return T::Z__CLASS::Z__CLASS_GET_FIELDS_MAP();
}
static const BaseObject::Properties* propertiesGetter() {
static type::BaseObject::Properties* properties = initProperties();
return properties;
}
static Type* createType() {
Type::Info info;
info.nameQualifier = T::Z__CLASS_TYPE_NAME();
info.polymorphicDispatcher = new PolymorphicDispatcher();
info.parent = T::getParentType();
return new Type(CLASS_ID, info);
}
public:
/**
* Get type describing this class.
* @return - &id:oatpp::data::mapping::type::Type;
*/
static Type* getType() {
static Type* type = createType();
return type;
}
};
}
/**
* ObjectWrapper for &l:DTO;. AKA `oatpp::Object<T>`.
* @tparam ObjT - class extended from &l:DTO;.
*/
template<class ObjT>
class DTOWrapper : public ObjectWrapper<ObjT, __class::Object<ObjT>> {
template<class Type>
friend class DTOWrapper;
public:
typedef ObjT TemplateObjectType;
typedef __class::Object<ObjT> TemplateObjectClass;
public:
OATPP_DEFINE_OBJECT_WRAPPER_DEFAULTS(DTOWrapper, TemplateObjectType, TemplateObjectClass)
template<class OtherT>
DTOWrapper(const OtherT& other)
: type::ObjectWrapper<ObjT, __class::Object<ObjT>>(other.m_ptr)
{}
template<class OtherT>
DTOWrapper(OtherT&& other)
: type::ObjectWrapper<ObjT, __class::Object<ObjT>>(std::move(other.m_ptr))
{}
static DTOWrapper createShared() {
return std::make_shared<TemplateObjectType>();
}
template<class T>
DTOWrapper& operator = (const DTOWrapper<T>& other) {
this->m_ptr = other.m_ptr;
return *this;
}
template<class T>
DTOWrapper& operator = (DTOWrapper<T>&& other) {
this->m_ptr = std::move(other.m_ptr);
return *this;
}
template<typename T,
typename enabled = typename std::enable_if<std::is_same<T, std::nullptr_t>::value, void>::type
>
inline bool operator == (T){
return this->m_ptr.get() == nullptr;
}
template<typename T,
typename enabled = typename std::enable_if<std::is_same<T, std::nullptr_t>::value, void>::type
>
inline bool operator != (T){
return this->m_ptr.get() != nullptr;
}
template<typename T,
typename enabled = typename std::enable_if<std::is_same<T, DTOWrapper>::value, void>::type
>
inline bool operator == (const T &other) const {
if(this->m_ptr.get() == other.m_ptr.get()) return true;
if(!this->m_ptr || !other.m_ptr) return false;
return *this->m_ptr == *other.m_ptr;
}
template<typename T,
typename enabled = typename std::enable_if<std::is_same<T, DTOWrapper>::value, void>::type
>
inline bool operator != (const T &other) const {
return !operator == (other);
}
static const std::unordered_map<std::string, BaseObject::Property*>& getPropertiesMap() {
auto dispatcher = static_cast<const __class::AbstractObject::PolymorphicDispatcher*>(
__class::Object<ObjT>::getType()->polymorphicDispatcher
);
return dispatcher->getProperties()->getMap();
}
static const std::list<BaseObject::Property*>& getPropertiesList() {
auto dispatcher = static_cast<const __class::AbstractObject::PolymorphicDispatcher*>(
__class::Object<ObjT>::getType()->polymorphicDispatcher
);
return dispatcher->getProperties()->getList();
}
static v_int64 getPropertiesCount() {
auto dispatcher = static_cast<const __class::AbstractObject::PolymorphicDispatcher*>(
__class::Object<ObjT>::getType()->polymorphicDispatcher
);
return dispatcher->getProperties()->getList().size();
}
ObjectWrapper<void>& operator[](const std::string& propertyName) {
return getPropertiesMap().at(propertyName)->getAsRef(this->m_ptr.get());
}
};
/**
* Base class for all DTO objects.
* For more info about Data Transfer Object (DTO) see [Data Transfer Object (DTO)](https://oatpp.io/docs/components/dto/).
*/
class DTO : public BaseObject {
template<class T>
friend class __class::Object;
private:
typedef DTO Z__CLASS;
typedef DTO Z__CLASS_EXTENDED;
public:
typedef oatpp::data::mapping::type::Void Void;
typedef oatpp::data::mapping::type::Any Any;
typedef oatpp::data::mapping::type::String String;
typedef oatpp::data::mapping::type::Int8 Int8;
typedef oatpp::data::mapping::type::UInt8 UInt8;
typedef oatpp::data::mapping::type::Int16 Int16;
typedef oatpp::data::mapping::type::UInt16 UInt16;
typedef oatpp::data::mapping::type::Int32 Int32;
typedef oatpp::data::mapping::type::UInt32 UInt32;
typedef oatpp::data::mapping::type::Int64 Int64;
typedef oatpp::data::mapping::type::UInt64 UInt64;
typedef oatpp::data::mapping::type::Float32 Float32;
typedef oatpp::data::mapping::type::Float64 Float64;
typedef oatpp::data::mapping::type::Boolean Boolean;
template <class T>
using Object = DTOWrapper<T>;
template <class T>
using Enum = oatpp::data::mapping::type::Enum<T>;
template <class T>
using Vector = oatpp::data::mapping::type::Vector<T>;
template <class T>
using UnorderedSet = oatpp::data::mapping::type::UnorderedSet<T>;
template <class T>
using List = oatpp::data::mapping::type::List<T>;
template <class Value>
using Fields = oatpp::data::mapping::type::PairList<String, Value>;
template <class Value>
using UnorderedFields = oatpp::data::mapping::type::UnorderedMap<String, Value>;
private:
static const mapping::type::Type* getParentType();
static const char* Z__CLASS_TYPE_NAME();
static data::mapping::type::BaseObject::Properties* Z__CLASS_GET_FIELDS_MAP();
static BaseObject::Properties* Z__CLASS_EXTEND(BaseObject::Properties* properties, BaseObject::Properties* extensionProperties);
public:
virtual v_uint64 defaultHashCode() const {
return (v_uint64) reinterpret_cast<v_buff_usize>(this);
}
virtual bool defaultEquals(const DTO& other) const {
return this == &other;
}
v_uint64 hashCode() const {
return defaultHashCode();
}
bool operator==(const DTO& other) const {
return defaultEquals(other);
}
};
}}}}
namespace std {
template<class T>
struct hash<oatpp::data::mapping::type::DTOWrapper<T>> {
typedef oatpp::data::mapping::type::DTOWrapper<T> argument_type;
typedef v_uint64 result_type;
result_type operator()(argument_type const &ow) const noexcept {
if(ow) {
return ow->hashCode();
}
return 0;
}
};
}
#endif /* oatpp_data_type_Object_hpp */
| vincent-in-black-sesame/oat | src/oatpp/core/data/mapping/type/Object.hpp | C++ | apache-2.0 | 13,105 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#include "PairList.hpp"
namespace oatpp { namespace data { namespace mapping { namespace type {
namespace __class {
const ClassId AbstractPairList::CLASS_ID("PairList");
}
}}}}
| vincent-in-black-sesame/oat | src/oatpp/core/data/mapping/type/PairList.cpp | C++ | apache-2.0 | 1,182 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef oatpp_data_mapping_type_PairList_hpp
#define oatpp_data_mapping_type_PairList_hpp
#include "./Map.hpp"
#include "./Type.hpp"
#include <list>
#include <initializer_list>
#include <utility>
namespace oatpp { namespace data { namespace mapping { namespace type {
namespace __class {
/**
* Abstract PairList class.
*/
class AbstractPairList {
public:
/**
* Class id.
*/
static const ClassId CLASS_ID;
};
template<class Key, class Value>
class PairList;
}
/**
* `ObjectWrapper` over `std::list<std::pair<Key, Value>>`
* @tparam Key - Key `ObjectWrapper` type.
* @tparam Value - Value `ObjectWrapper` type.
* @tparam C - Class.
*/
template<class Key, class Value, class C>
class PairListObjectWrapper : public type::ObjectWrapper<std::list<std::pair<Key, Value>>, C> {
public:
typedef std::list<std::pair<Key, Value>> TemplateObjectType;
typedef C TemplateObjectClass;
public:
OATPP_DEFINE_OBJECT_WRAPPER_DEFAULTS(PairListObjectWrapper, TemplateObjectType, TemplateObjectClass)
PairListObjectWrapper(std::initializer_list<std::pair<Key, Value>> ilist)
: type::ObjectWrapper<TemplateObjectType, TemplateObjectClass>(std::make_shared<TemplateObjectType>(ilist))
{}
static PairListObjectWrapper createShared() {
return std::make_shared<TemplateObjectType>();
}
PairListObjectWrapper& operator = (std::initializer_list<std::pair<Key, Value>> ilist) {
this->m_ptr = std::make_shared<TemplateObjectType>(ilist);
return *this;
}
std::pair<Key, Value>& operator[] (v_buff_usize index) const {
auto it = this->m_ptr->begin();
std::advance(it, index);
return *it;
}
Value& operator[] (const Key& key) const {
auto& list = *(this->m_ptr.get());
auto it = list.begin();
while(it != list.end()) {
if(it->first == key) {
return it->second;
}
it ++;
}
list.push_back({key, nullptr});
return list.back().second;
}
Value getValueByKey(const Key& key, const Value& defValue = nullptr) const {
auto& list = *(this->m_ptr.get());
auto it = list.begin();
while(it != list.end()) {
if(it->first == key) {
return it->second;
}
it ++;
}
return defValue;
}
TemplateObjectType& operator*() const {
return this->m_ptr.operator*();
}
};
/**
* Mapping-Enables PairList<Key, Value>. See &l:PairListObjectWrapper;.
*/
template<class Key, class Value>
using PairList = PairListObjectWrapper<Key, Value, __class::PairList<Key, Value>>;
namespace __class {
template<class Key, class Value>
class PairList : public AbstractPairList {
private:
static Type createType() {
Type::Info info;
info.params.push_back(Key::Class::getType());
info.params.push_back(Value::Class::getType());
info.polymorphicDispatcher =
new typename __class::StandardMap<std::list<std::pair<Key, Value>>, Key, Value, PairList>::PolymorphicDispatcher();
info.isMap = true;
return Type(__class::AbstractPairList::CLASS_ID, info);
}
public:
static Type* getType() {
static Type type = createType();
return &type;
}
};
}
}}}}
#endif // oatpp_data_mapping_type_PairList_hpp
| vincent-in-black-sesame/oat | src/oatpp/core/data/mapping/type/PairList.hpp | C++ | apache-2.0 | 4,185 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#include "./Primitive.hpp"
#include "oatpp/core/data/stream/BufferStream.hpp"
#include "oatpp/core/utils/ConversionUtils.hpp"
#include "oatpp/core/data/share/MemoryLabel.hpp"
#include <fstream>
namespace oatpp { namespace data { namespace mapping { namespace type {
String::String(const std::shared_ptr<std::string>& ptr, const type::Type* const valueType)
: oatpp::data::mapping::type::ObjectWrapper<std::string, __class::String>(ptr)
{
if(type::__class::String::getType() != valueType) {
throw std::runtime_error("Value type does not match");
}
}
String String::loadFromFile(const char* filename) {
std::ifstream file (filename, std::ios::in|std::ios::binary|std::ios::ate);
if (file.is_open()) {
auto result = data::mapping::type::String(file.tellg());
file.seekg(0, std::ios::beg);
file.read((char*) result->data(), result->size());
file.close();
return result;
}
return nullptr;
}
void String::saveToFile(const char* filename) const {
std::ofstream fs(filename, std::ios::out | std::ios::binary);
if(m_ptr != nullptr) {
fs.write(m_ptr->data(), m_ptr->size());
}
fs.close();
}
const std::string& String::operator*() const {
return this->m_ptr.operator*();
}
bool String::equalsCI_ASCII(const std::string& other) {
auto ciLabel = share::StringKeyLabelCI(m_ptr);
return ciLabel == other;
}
bool String::equalsCI_ASCII(const String& other) {
auto ciLabel = share::StringKeyLabelCI(m_ptr);
return ciLabel == other;
}
bool String::equalsCI_ASCII(const char* other) {
auto ciLabel = share::StringKeyLabelCI(m_ptr);
return ciLabel == other;
}
std::string String::getValue(const std::string& defaultValue) const {
if(m_ptr) {
return *m_ptr;
}
return defaultValue;
}
String operator + (const char* a, const String& b) {
data::stream::BufferOutputStream stream;
stream << a << b;
return stream.toString();
}
String operator + (const String& a, const char* b) {
data::stream::BufferOutputStream stream;
stream << a << b;
return stream.toString();
}
String operator + (const String& a, const String& b) {
data::stream::BufferOutputStream stream;
stream << a << b;
return stream.toString();
}
namespace __class {
const ClassId String::CLASS_ID("String");
const ClassId Int8::CLASS_ID("Int8");
const ClassId UInt8::CLASS_ID("UInt8");
const ClassId Int16::CLASS_ID("Int16");
const ClassId UInt16::CLASS_ID("UInt16");
const ClassId Int32::CLASS_ID("Int32");
const ClassId UInt32::CLASS_ID("UInt32");
const ClassId Int64::CLASS_ID("Int64");
const ClassId UInt64::CLASS_ID("UInt64");
const ClassId Float32::CLASS_ID("Float32");
const ClassId Float64::CLASS_ID("Float64");
const ClassId Boolean::CLASS_ID("Boolean");
Type* String::getType(){
static Type type(CLASS_ID);
return &type;
}
Type* Int8::getType(){
static Type type(CLASS_ID);
return &type;
}
Type* UInt8::getType(){
static Type type(CLASS_ID);
return &type;
}
Type* Int16::getType(){
static Type type(CLASS_ID);
return &type;
}
Type* UInt16::getType(){
static Type type(CLASS_ID);
return &type;
}
Type* Int32::getType(){
static Type type(CLASS_ID);
return &type;
}
Type* UInt32::getType(){
static Type type(CLASS_ID);
return &type;
}
Type* Int64::getType(){
static Type type(CLASS_ID);
return &type;
}
Type* UInt64::getType(){
static Type type(CLASS_ID);
return &type;
}
Type* Float32::getType(){
static Type type(CLASS_ID);
return &type;
}
Type* Float64::getType(){
static Type type(CLASS_ID);
return &type;
}
Type* Boolean::getType(){
static Type type(CLASS_ID);
return &type;
}
}
}}}}
| vincent-in-black-sesame/oat | src/oatpp/core/data/mapping/type/Primitive.cpp | C++ | apache-2.0 | 4,731 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef oatpp_data_type_Primitive_hpp
#define oatpp_data_type_Primitive_hpp
#include "./Type.hpp"
#include "oatpp/core/base/Countable.hpp"
#include <algorithm>
#include <cctype>
#include <iterator>
namespace oatpp { namespace data { namespace mapping { namespace type {
namespace __class {
class String; // FWD
class Int8; // FWD
class UInt8; // FWD
class Int16; // FWD
class UInt16; // FWD
class Int32; // FWD
class UInt32; // FWD
class Int64; // FWD
class UInt64; // FWD
class Float32; // FWD
class Float64; // FWD
class Boolean; // FWD
}
/**
* Mapping-enables String is &id:type::ObjectWrapper; over `std::string`;
*/
class String : public type::ObjectWrapper<std::string, __class::String> {
public:
String(const std::shared_ptr<std::string>& ptr, const type::Type* const valueType);
public:
String() {}
explicit String(v_buff_size size)
: type::ObjectWrapper<std::string, __class::String>(std::make_shared<std::string>(size, '\0'))
{}
String(const char* data, v_buff_size size)
: type::ObjectWrapper<std::string, __class::String>(std::make_shared<std::string>(data, size))
{}
template<typename T,
typename enabled = typename std::enable_if<std::is_same<T, std::nullptr_t>::value, void>::type
>
String(T) {}
template<typename T,
typename enabled = typename std::enable_if<std::is_same<T, char>::value, void>::type
>
String(const T* data)
: type::ObjectWrapper<std::string, __class::String>(
data == nullptr ? nullptr : std::make_shared<std::string>(data)
)
{}
template<typename T,
typename enabled = typename std::enable_if<std::is_same<T, std::string>::value, void>::type
>
String(const T& str)
: type::ObjectWrapper<std::string, __class::String>(std::make_shared<std::string>(str))
{}
template<typename T,
typename enabled = typename std::enable_if<std::is_same<T, std::string>::value, void>::type
>
String(T&& str)
: type::ObjectWrapper<std::string, __class::String>(
std::make_shared<std::string>(std::forward<std::string>(str))
)
{}
String(const std::shared_ptr<std::string>& ptr)
: type::ObjectWrapper<std::string, __class::String>(ptr)
{}
String(std::shared_ptr<std::string>&& ptr)
: type::ObjectWrapper<std::string, __class::String>(std::forward<std::shared_ptr<std::string>>(ptr))
{}
String(const String& other)
: type::ObjectWrapper<std::string, __class::String>(other)
{}
String(String&& other)
: type::ObjectWrapper<std::string, __class::String>(std::forward<String>(other))
{}
/**
* Load data from file and store in &id:oatpp::String;.
* @param filename - name of the file.
* @return - &id:oatpp::String;.
*/
static String loadFromFile(const char* filename);
/**
* Save content of the buffer to file.
* @param filename - name of the file.
*/
void saveToFile(const char* filename) const;
const std::string& operator*() const;
operator std::string() const {
if (this->m_ptr == nullptr) {
throw std::runtime_error("[oatpp::data::mapping::type::String::operator std::string() const]: "
"Error. Null pointer.");
}
return this->m_ptr.operator*();
}
template<typename T,
typename enabled = typename std::enable_if<std::is_same<T, std::nullptr_t>::value, void>::type
>
inline String& operator = (std::nullptr_t) {
m_ptr.reset();
return *this;
}
template<typename T,
typename enabled = typename std::enable_if<std::is_same<T, char>::value, void>::type
>
inline String& operator = (const T* str) {
if (str) {
m_ptr = std::make_shared<std::string>(str);
} else {
m_ptr.reset();
}
return *this;
}
template<typename T,
typename enabled = typename std::enable_if<std::is_same<T, std::string>::value, void>::type
>
inline String& operator = (const T& str) {
m_ptr = std::make_shared<std::string>(str);
return *this;
}
template<typename T,
typename enabled = typename std::enable_if<std::is_same<T, std::string>::value, void>::type
>
inline String& operator = (T&& str) {
m_ptr = std::make_shared<std::string>(std::forward<std::string>(str));
return *this;
}
inline String& operator = (const String& other){
m_ptr = other.m_ptr;
return *this;
}
inline String& operator = (String&& other) noexcept {
m_ptr = std::move(other.m_ptr);
return *this;
}
/**
* Case insensitive compare (ASCII only).
* @param other
* @return
*/
bool equalsCI_ASCII(const std::string& other);
/**
* Case insensitive compare (ASCII only).
* @param other
* @return
*/
bool equalsCI_ASCII(const String& other);
/**
* Case insensitive compare (ASCII only).
* @param other
* @return
*/
bool equalsCI_ASCII(const char* str);
/**
* Get underlying value.
* @param defaultValue - value to return in case stored value is `nullptr`.
* @return - value or `defaultValue` if stored value is `nullptr`.
*/
std::string getValue(const std::string& defaultValue) const;
template<typename T,
typename enabled = typename std::enable_if<std::is_same<T, std::nullptr_t>::value, void>::type
>
inline bool operator == (T) const {
return m_ptr.get() == nullptr;
}
template<typename T,
typename enabled = typename std::enable_if<std::is_same<T, std::nullptr_t>::value, void>::type
>
inline bool operator != (T) const {
return m_ptr.get() != nullptr;
}
template<typename T,
typename enabled = typename std::enable_if<std::is_same<T, char>::value, void>::type
>
inline bool operator == (const T* str) const {
if(!m_ptr) return str == nullptr;
if(str == nullptr) return false;
return *m_ptr == str;
}
template<typename T,
typename enabled = typename std::enable_if<std::is_same<T, char>::value, void>::type
>
inline bool operator != (const T* str) const {
return !operator == (str);
}
template<typename T,
typename enabled = typename std::enable_if<std::is_same<T, std::string>::value, void>::type
>
inline bool operator == (const T& str) const {
if(!m_ptr) return false;
return *m_ptr == str;
}
template<typename T,
typename enabled = typename std::enable_if<std::is_same<T, std::string>::value, void>::type
>
inline bool operator != (const T& str) const {
return !operator == (str);
}
inline bool operator == (const String &other) const {
if(!m_ptr) return !other.m_ptr;
if(!other.m_ptr) return false;
return *m_ptr == *other.m_ptr;
}
inline bool operator != (const String &other) const {
return !operator == (other);
}
};
String operator + (const char* a, const String& b);
String operator + (const String& a, const char* b);
String operator + (const String& a, const String& b);
/**
* Template for primitive mapping-enabled types.
* @tparam TValueType - type of the value ex.: v_int64.
* @tparam Clazz - Class holding static class information.
*/
template<typename TValueType, class Clazz>
class Primitive : public type::ObjectWrapper<TValueType, Clazz> {
public:
typedef TValueType UnderlyingType;
public:
OATPP_DEFINE_OBJECT_WRAPPER_DEFAULTS(Primitive, TValueType, Clazz)
Primitive(TValueType value)
: type::ObjectWrapper<TValueType, Clazz>(std::make_shared<TValueType>(value))
{}
Primitive& operator = (TValueType value) {
this->m_ptr = std::make_shared<TValueType>(value);
return *this;
}
TValueType operator*() const {
return this->m_ptr.operator*();
}
template<typename T,
typename enabled = typename std::enable_if<std::is_same<T, std::nullptr_t>::value, void>::type
>
inline bool operator == (T){
return this->m_ptr.get() == nullptr;
}
template<typename T,
typename enabled = typename std::enable_if<std::is_same<T, std::nullptr_t>::value, void>::type
>
inline bool operator != (T){
return this->m_ptr.get() != nullptr;
}
template<typename T,
typename enabled = typename std::enable_if<std::is_same<T, TValueType>::value, void>::type
>
inline bool operator == (T value) const {
if(!this->m_ptr) return false;
return *this->m_ptr == value;
}
template<typename T,
typename enabled = typename std::enable_if<std::is_same<T, TValueType>::value, void>::type
>
inline bool operator != (T value) const {
if(!this->m_ptr) return true;
return *this->m_ptr != value;
}
template<typename T,
typename enabled = typename std::enable_if<std::is_same<T, Primitive>::value, void>::type
>
inline bool operator == (const T &other) const {
if(this->m_ptr.get() == other.m_ptr.get()) return true;
if(!this->m_ptr || !other.m_ptr) return false;
return *this->m_ptr == *other.m_ptr;
}
template<typename T,
typename enabled = typename std::enable_if<std::is_same<T, Primitive>::value, void>::type
>
inline bool operator != (const T &other) const {
return !operator == (other);
}
inline operator TValueType() const {
return *this->m_ptr;
}
TValueType getValue(const TValueType& defaultValue) const {
if(this->m_ptr) {
return *this->m_ptr;
}
return defaultValue;
}
};
/**
* ObjectWrapper for Boolean.
*/
class Boolean : public type::ObjectWrapper<bool, __class::Boolean> {
public:
typedef bool UnderlyingType;
public:
OATPP_DEFINE_OBJECT_WRAPPER_DEFAULTS(Boolean, bool, __class::Boolean)
Boolean(bool value)
: type::ObjectWrapper<bool, __class::Boolean>(std::make_shared<bool>(value))
{}
Boolean& operator = (bool value) {
this->m_ptr = std::make_shared<bool>(value);
return *this;
}
inline bool operator*() const {
return this->m_ptr.operator*();
}
template<typename T,
typename enabled = typename std::enable_if<std::is_same<T, std::nullptr_t>::value, void>::type
>
inline bool operator == (T){
return m_ptr.get() == nullptr;
}
template<typename T,
typename enabled = typename std::enable_if<std::is_same<T, std::nullptr_t>::value, void>::type
>
inline bool operator != (T){
return m_ptr.get() != nullptr;
}
template<typename T,
typename enabled = typename std::enable_if<std::is_same<T, bool>::value, void>::type
>
inline bool operator == (T value) const {
if(!this->m_ptr) return false;
return *this->m_ptr == value;
}
template<typename T,
typename enabled = typename std::enable_if<std::is_same<T, bool>::value, void>::type
>
inline bool operator != (T value) const {
if(!this->m_ptr) return true;
return *this->m_ptr != value;
}
inline bool operator == (const Boolean &other) const {
if(this->m_ptr.get() == other.m_ptr.get()) return true;
if(!this->m_ptr || !other.m_ptr) return false;
return *this->m_ptr == *other.m_ptr;
}
inline bool operator != (const Boolean &other) const {
return !operator == (other);
}
inline operator bool() const {
if(this->m_ptr) {
return *(this->m_ptr);
}
return false;
}
bool getValue(bool defaultValue) const {
if(this->m_ptr) {
return *this->m_ptr;
}
return defaultValue;
}
};
/**
* Int8 is an ObjectWrapper over `v_int8` and __class::Int8.
*/
typedef Primitive<v_int8, __class::Int8> Int8;
/**
* UInt8 is an ObjectWrapper over `v_uint8` and __class::UInt8.
*/
typedef Primitive<v_uint8, __class::UInt8> UInt8;
/**
* Int16 is an ObjectWrapper over `v_int16` and __class::Int16.
*/
typedef Primitive<v_int16, __class::Int16> Int16;
/**
* UInt16 is an ObjectWrapper over `v_uint16` and __class::UInt16.
*/
typedef Primitive<v_uint16, __class::UInt16> UInt16;
/**
* Int32 is an ObjectWrapper over `v_int32` and __class::Int32.
*/
typedef Primitive<v_int32, __class::Int32> Int32;
/**
* UInt32 is an ObjectWrapper over `v_uint32` and __class::UInt32.
*/
typedef Primitive<v_uint32, __class::UInt32> UInt32;
/**
* Int64 is an ObjectWrapper over `v_int64` and __class::Int64.
*/
typedef Primitive<v_int64, __class::Int64> Int64;
/**
* UInt64 is an ObjectWrapper over `v_uint64` and __class::UInt64.
*/
typedef Primitive<v_uint64, __class::UInt64> UInt64;
/**
* Float32 is an ObjectWrapper over `v_float32` and __class::Float32.
*/
typedef Primitive<v_float32, __class::Float32> Float32;
/**
* Float64 is an ObjectWrapper over `v_float64` and __class::Float64.
*/
typedef Primitive<v_float64, __class::Float64> Float64;
template<>
struct ObjectWrapperByUnderlyingType <v_int8> {
typedef Int8 ObjectWrapper;
};
template<>
struct ObjectWrapperByUnderlyingType <v_uint8> {
typedef UInt8 ObjectWrapper;
};
template<>
struct ObjectWrapperByUnderlyingType <v_int16> {
typedef Int16 ObjectWrapper;
};
template<>
struct ObjectWrapperByUnderlyingType <v_uint16> {
typedef UInt16 ObjectWrapper;
};
template<>
struct ObjectWrapperByUnderlyingType <v_int32> {
typedef Int32 ObjectWrapper;
};
template<>
struct ObjectWrapperByUnderlyingType <v_uint32> {
typedef UInt32 ObjectWrapper;
};
template<>
struct ObjectWrapperByUnderlyingType <v_int64> {
typedef Int64 ObjectWrapper;
};
template<>
struct ObjectWrapperByUnderlyingType <v_uint64> {
typedef UInt64 ObjectWrapper;
};
template<>
struct ObjectWrapperByUnderlyingType <bool> {
typedef Boolean ObjectWrapper;
};
namespace __class {
class String {
public:
static const ClassId CLASS_ID;
static Type* getType();
};
class Int8 {
public:
static const ClassId CLASS_ID;
static Type* getType();
};
class UInt8 {
public:
static const ClassId CLASS_ID;
static Type* getType();
};
class Int16 {
public:
static const ClassId CLASS_ID;
static Type* getType();
};
class UInt16 {
public:
static const ClassId CLASS_ID;
static Type* getType();
};
class Int32 {
public:
static const ClassId CLASS_ID;
static Type* getType();
};
class UInt32 {
public:
static const ClassId CLASS_ID;
static Type* getType();
};
class Int64 {
public:
static const ClassId CLASS_ID;
static Type* getType();
};
class UInt64 {
public:
static const ClassId CLASS_ID;
static Type* getType();
};
class Float32 {
public:
static const ClassId CLASS_ID;
static Type* getType();
};
class Float64 {
public:
static const ClassId CLASS_ID;
static Type* getType();
};
class Boolean {
public:
static const ClassId CLASS_ID;
static Type* getType();
};
}
}}}}
namespace std {
template<>
struct hash<oatpp::data::mapping::type::String> {
typedef oatpp::data::mapping::type::String argument_type;
typedef v_uint64 result_type;
result_type operator()(argument_type const& s) const noexcept {
if(s.get() == nullptr) return 0;
return hash<std::string> {} (*s);
}
};
template<>
struct hash<oatpp::data::mapping::type::Boolean> {
typedef oatpp::data::mapping::type::Boolean argument_type;
typedef v_uint64 result_type;
result_type operator()(argument_type const& v) const noexcept {
if(v.get() == nullptr) return 2;
return result_type(*v);
}
};
template<>
struct hash<oatpp::data::mapping::type::Int8> {
typedef oatpp::data::mapping::type::Int8 argument_type;
typedef v_uint64 result_type;
result_type operator()(argument_type const& v) const noexcept {
if(v.get() == nullptr) return 0;
return (result_type) *v;
}
};
template<>
struct hash<oatpp::data::mapping::type::UInt8> {
typedef oatpp::data::mapping::type::UInt8 argument_type;
typedef v_uint64 result_type;
result_type operator()(argument_type const& v) const noexcept {
if(v.get() == nullptr) return 0;
return (result_type) *v;
}
};
template<>
struct hash<oatpp::data::mapping::type::Int16> {
typedef oatpp::data::mapping::type::Int16 argument_type;
typedef v_uint64 result_type;
result_type operator()(argument_type const& v) const noexcept {
if(v.get() == nullptr) return 0;
return (result_type) *v;
}
};
template<>
struct hash<oatpp::data::mapping::type::UInt16> {
typedef oatpp::data::mapping::type::UInt16 argument_type;
typedef v_uint64 result_type;
result_type operator()(argument_type const& v) const noexcept {
if(v.get() == nullptr) return 0;
return (result_type) *v;
}
};
template<>
struct hash<oatpp::data::mapping::type::Int32> {
typedef oatpp::data::mapping::type::Int32 argument_type;
typedef v_uint64 result_type;
result_type operator()(argument_type const& v) const noexcept {
if(v.get() == nullptr) return 0;
return (result_type) *v;
}
};
template<>
struct hash<oatpp::data::mapping::type::UInt32> {
typedef oatpp::data::mapping::type::UInt32 argument_type;
typedef v_uint64 result_type;
result_type operator()(argument_type const& v) const noexcept {
if(v.get() == nullptr) return 0;
return (result_type) *v;
}
};
template<>
struct hash<oatpp::data::mapping::type::Int64> {
typedef oatpp::data::mapping::type::Int64 argument_type;
typedef v_uint64 result_type;
result_type operator()(argument_type const& v) const noexcept {
if(v.get() == nullptr) return 0;
return (result_type) *v;
}
};
template<>
struct hash<oatpp::data::mapping::type::UInt64> {
typedef oatpp::data::mapping::type::UInt64 argument_type;
typedef v_uint64 result_type;
result_type operator()(argument_type const& v) const noexcept {
if(v.get() == nullptr) return 0;
return (result_type) *v;
}
};
template<>
struct hash<oatpp::data::mapping::type::Float32> {
typedef oatpp::data::mapping::type::Float32 argument_type;
typedef v_uint64 result_type;
result_type operator()(argument_type const& v) const noexcept {
if(v.get() == nullptr) return 0;
return *((v_uint32*) v.get());
}
};
template<>
struct hash<oatpp::data::mapping::type::Float64> {
typedef oatpp::data::mapping::type::Float64 argument_type;
typedef v_uint64 result_type;
result_type operator()(argument_type const& v) const noexcept {
if(v.get() == nullptr) return 0;
return *((result_type*) v.get());
}
};
}
#endif /* oatpp_base_Countable_PrimitiveDataTypes_hpp */
| vincent-in-black-sesame/oat | src/oatpp/core/data/mapping/type/Primitive.hpp | C++ | apache-2.0 | 19,334 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#include "Type.hpp"
namespace oatpp { namespace data { namespace mapping { namespace type {
namespace __class {
const ClassId Void::CLASS_ID("Void");
Type* Void::getType(){
static Type type(CLASS_ID);
return &type;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ClassId
std::mutex& ClassId::getClassMutex() {
static std::mutex classMutex;
return classMutex;
}
std::vector<const char*>& ClassId::getClassNames() {
static std::vector<const char*> classNames;
return classNames;
}
v_int32 ClassId::registerClassName(const char* name) {
std::lock_guard<std::mutex> lock(getClassMutex());
getClassNames().push_back(name);
return getClassNames().size() - 1;
}
ClassId::ClassId(const char* pName)
: name(pName)
, id(registerClassName(pName))
{}
int ClassId::getClassCount() {
std::lock_guard<std::mutex> lock(getClassMutex());
return getClassNames().size();
}
std::vector<const char*> ClassId::getRegisteredClassNames() {
std::lock_guard<std::mutex> lock(getClassMutex());
return std::vector<const char*>(getClassNames());
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Type
Type::Type(const ClassId& pClassId, const Info& typeInfo)
: classId(pClassId)
, nameQualifier(typeInfo.nameQualifier)
, params(typeInfo.params)
, polymorphicDispatcher(typeInfo.polymorphicDispatcher)
, interpretationMap(typeInfo.interpretationMap)
, parent(typeInfo.parent)
, isCollection(typeInfo.isCollection)
, isMap(typeInfo.isMap)
{}
const Type::AbstractInterpretation* Type::findInterpretation(const std::vector<std::string>& names) const {
for(const std::string& name : names) {
auto it = interpretationMap.find(name);
if(it != interpretationMap.end()) {
return it->second;
}
}
return nullptr;
}
bool Type::extends(const Type* other) const {
const Type* curr = this;
while(curr != nullptr) {
if(curr == other) {
return true;
}
curr = curr->parent;
}
return false;
}
}}}}
| vincent-in-black-sesame/oat | src/oatpp/core/data/mapping/type/Type.cpp | C++ | apache-2.0 | 3,131 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef oatpp_data_type_Type_hpp
#define oatpp_data_type_Type_hpp
#include "oatpp/core/base/Countable.hpp"
#include "oatpp/core/base/Environment.hpp"
#include <list>
#include <unordered_map>
#include <vector>
#include <string>
namespace oatpp { namespace data { namespace mapping { namespace type {
class Type; // FWD
/**
* Structure representing `ID` of the type class.
*/
class ClassId {
private:
static std::mutex& getClassMutex();
static std::vector<const char*>& getClassNames();
static v_int32 registerClassName(const char* name);
public:
/**
* Get count of all type classes created.
* @return
*/
static int getClassCount();
/**
* Get registered class names.
* @return
*/
static std::vector<const char*> getRegisteredClassNames();
public:
/**
* Constructor.
* @param pName
*/
ClassId(const char* pName);
/**
* Name of the type class.
*/
const char* const name;
/**
* Integer ID of the type class. <br>
* *Note: class type IDs are integer values incremented continuously from [0 to `getClassCount()`]*
*/
const v_int32 id;
public:
inline bool operator == (const ClassId& other) const {
return id == other.id;
}
inline bool operator != (const ClassId& other) const {
return id != other.id;
}
};
namespace __class {
/**
* Void Object Class.
*/
class Void {
public:
/**
* Class id.
*/
static const ClassId CLASS_ID;
/**
* Get class type information.
* @return - &l:Type;
*/
static Type* getType();
};
}
class Void; // FWD
/**
* ObjectWrapper holds std::shared_ptr to object, object static type, plus object dynamic type information.
* @tparam T - Object Type.
* @tparam Clazz - Static type info.
*/
template <class T, class Clazz = __class::Void>
class ObjectWrapper {
friend Void;
template <class Q, class W>
friend class ObjectWrapper;
protected:
static void checkType(const Type* _this, const Type* other);
protected:
std::shared_ptr<T> m_ptr;
const Type* m_valueType;
public:
/**
* Static object type
*/
typedef T ObjectType;
/**
* Static object class information.
*/
typedef Clazz Class;
public:
ObjectWrapper(const std::shared_ptr<T>& ptr)
: m_ptr(ptr)
, m_valueType(Class::getType())
{}
ObjectWrapper(const std::shared_ptr<T>& ptr, const Type* const type)
: m_ptr(ptr)
, m_valueType(type)
{}
ObjectWrapper(std::shared_ptr<T>&& ptr, const Type* const type)
: m_ptr(std::move(ptr))
, m_valueType(type)
{}
public:
ObjectWrapper()
: m_valueType(Class::getType())
{}
ObjectWrapper(std::nullptr_t)
: m_valueType(Class::getType())
{}
ObjectWrapper(const Type* const type)
: m_valueType(type)
{}
ObjectWrapper(const ObjectWrapper& other)
: m_ptr(other.m_ptr)
, m_valueType(other.m_valueType)
{}
ObjectWrapper(ObjectWrapper&& other)
: m_ptr(std::move(other.m_ptr))
, m_valueType(other.m_valueType)
{}
template <class Q, class W>
ObjectWrapper(const ObjectWrapper<Q, W>& other)
: m_ptr(other.m_ptr)
, m_valueType(other.m_valueType)
{}
template <class Q, class W>
ObjectWrapper(ObjectWrapper<Q, W>&& other)
: m_ptr(std::move(other.m_ptr))
, m_valueType(other.m_valueType)
{}
inline ObjectWrapper& operator=(const ObjectWrapper& other){
checkType(m_valueType, other.m_valueType);
m_ptr = other.m_ptr;
return *this;
}
inline ObjectWrapper& operator=(ObjectWrapper&& other){
checkType(m_valueType, other.m_valueType);
m_ptr = std::move(other.m_ptr);
return *this;
}
template <class Q, class W>
inline ObjectWrapper& operator=(const ObjectWrapper<Q, W>& other){
checkType(m_valueType, other.m_valueType);
m_ptr = other.m_ptr;
return *this;
}
template <class Q, class W>
inline ObjectWrapper& operator=(ObjectWrapper<Q, W>&& other){
checkType(m_valueType, other.m_valueType);
m_ptr = std::move(other.m_ptr);
return *this;
}
template<class Wrapper>
Wrapper cast() const;
inline T* operator->() const {
return m_ptr.operator->();
}
T* get() const {
return m_ptr.get();
}
void resetPtr(const std::shared_ptr<T>& ptr = nullptr) {
m_ptr = ptr;
}
std::shared_ptr<T> getPtr() const {
return m_ptr;
}
inline bool operator == (std::nullptr_t) const {
return m_ptr.get() == nullptr;
}
inline bool operator != (std::nullptr_t) const {
return m_ptr.get() != nullptr;
}
inline bool operator == (const ObjectWrapper& other) const {
return m_ptr.get() == other.m_ptr.get();
}
inline bool operator != (const ObjectWrapper& other) const {
return m_ptr.get() != other.m_ptr.get();
}
explicit inline operator bool() const {
return m_ptr.operator bool();
}
/**
* Get value type
* @return
*/
const Type* getValueType() const {
return m_valueType;
}
};
class Void : public ObjectWrapper<void, __class::Void> {
public:
Void(const std::shared_ptr<void>& ptr, const type::Type* const valueType)
: ObjectWrapper<void, __class::Void>(ptr, valueType)
{}
public:
Void() {}
template<typename T,
typename enabled = typename std::enable_if<std::is_same<T, std::nullptr_t>::value, void>::type
>
Void(T) {}
Void(const Type* const type)
: ObjectWrapper<void, __class::Void>(type)
{}
Void(const std::shared_ptr<void>& ptr)
: type::ObjectWrapper<void, __class::Void>(ptr)
{}
Void(std::shared_ptr<void>&& ptr)
: type::ObjectWrapper<void, __class::Void>(std::forward<std::shared_ptr<void>>(ptr))
{}
Void(const Void& other)
: type::ObjectWrapper<void, __class::Void>(other.getPtr(), other.getValueType())
{}
Void(Void&& other)
: type::ObjectWrapper<void, __class::Void>(std::move(other.getPtr()), other.getValueType())
{}
template<typename T, typename C>
Void(const ObjectWrapper<T, C>& other)
: type::ObjectWrapper<void, __class::Void>(other.getPtr(), other.getValueType())
{}
template<typename T, typename C>
Void(ObjectWrapper<T, C>&& other)
: type::ObjectWrapper<void, __class::Void>(std::move(other.getPtr()), other.getValueType())
{}
template<typename T,
typename enabled = typename std::enable_if<std::is_same<T, std::nullptr_t>::value, void>::type
>
inline Void& operator = (std::nullptr_t) {
m_ptr.reset();
return *this;
}
inline Void& operator = (const Void& other){
m_ptr = other.m_ptr;
m_valueType = other.getValueType();
return *this;
}
inline Void& operator = (Void&& other){
m_ptr = std::move(other.m_ptr);
m_valueType = other.getValueType();
return *this;
}
template<typename T, typename C>
inline Void& operator = (const ObjectWrapper<T, C>& other){
m_ptr = other.m_ptr;
m_valueType = other.getValueType();
return *this;
}
template<typename T, typename C>
inline Void& operator = (ObjectWrapper<T, C>&& other){
m_ptr = std::move(other.m_ptr);
m_valueType = other.getValueType();
return *this;
}
template<typename T,
typename enabled = typename std::enable_if<std::is_same<T, std::nullptr_t>::value, void>::type
>
inline bool operator == (T) const {
return m_ptr.get() == nullptr;
}
template<typename T,
typename enabled = typename std::enable_if<std::is_same<T, std::nullptr_t>::value, void>::type
>
inline bool operator != (T) const {
return m_ptr.get() != nullptr;
}
template<typename T, typename C>
inline bool operator == (const ObjectWrapper<T, C> &other) const {
return m_ptr.get() == other.get();
}
template<typename T, typename C>
inline bool operator != (const ObjectWrapper<T, C> &other) const {
return m_ptr.get() != other.get();
}
};
template <typename T>
struct ObjectWrapperByUnderlyingType {};
/**
* Object type data.
*/
class Type {
public:
/**
* Type Abstract Interpretation.
*/
class AbstractInterpretation {
public:
virtual ~AbstractInterpretation() = default;
/**
* Convert the object to its interpretation.
* @param originalValue
* @return
*/
virtual Void toInterpretation(const Void& originalValue) const = 0;
/**
* Convert interpretation back to the original object.
* @param interValue
* @return
*/
virtual Void fromInterpretation(const Void& interValue) const = 0;
/**
* Type of the interpretation.
* @return
*/
virtual const Type* getInterpretationType() const = 0;
};
template<class OriginalWrapper, class InterWrapper>
class Interpretation : public AbstractInterpretation {
public:
Void toInterpretation(const Void& originalValue) const override {
return interpret(originalValue.template cast<OriginalWrapper>());
}
Void fromInterpretation(const Void& interValue) const override {
return reproduce(interValue.template cast<InterWrapper>());
}
const Type* getInterpretationType() const override {
return InterWrapper::Class::getType();
}
public:
virtual InterWrapper interpret(const OriginalWrapper& value) const = 0;
virtual OriginalWrapper reproduce(const InterWrapper& value) const = 0;
};
typedef std::unordered_map<std::string, const AbstractInterpretation*> InterpretationMap;
public:
/**
* Type info.
*/
struct Info {
/**
* Default constructor.
*/
Info() {}
/**
* Type name qualifier.
*/
const char* nameQualifier = nullptr;
/**
* List of type parameters - for templated types.
*/
std::vector<const Type*> params;
/**
* PolymorphicDispatcher is responsible for forwarding polymorphic calls to a correct object of type `Type`.
*/
void* polymorphicDispatcher = nullptr;
/**
* Map of type Interpretations.
*/
InterpretationMap interpretationMap;
/**
* Parent type. <br>
* Ex.: DTO super-class type. <br>
* **Note:** setting `parent` type also means that child object can be
* statically casted to parent type without any violations.
*/
const Type* parent = nullptr;
/**
* polymorphicDispatcher extends &id:oatpp::data::mapping::type::__class::Collection::PolymorphicDispatcher;.
*/
bool isCollection = false;
/**
* polymorphicDispatcher extends &id:oatpp::data::mapping::type::__class::Map::PolymorphicDispatcher;.
*/
bool isMap = false;
};
public:
/**
* Constructor.
* @param pClassId - type class id.
* @param typeInfo - type creation info. &l:Type::Info;.
*/
Type(const ClassId& pClassId, const Info& typeInfo = Info());
/**
* type class id.
*/
const ClassId classId;
/**
* Type name qualifier.
*/
const char* const nameQualifier;
/**
* List of type parameters - for templated types.
*/
const std::vector<const Type*> params;
/**
* PolymorphicDispatcher - is an object to forward polymorphic calls to a correct object of type `Type`.
*/
const void* const polymorphicDispatcher;
/**
* Map of type Interpretations.
*/
const InterpretationMap interpretationMap;
/**
* Parent type. <br>
* Ex.: DTO super-class type. <br>
* **Note:** setting `parent` type also means that child object can be
* statically casted to parent type without any violations.
*/
const Type* const parent;
/**
* polymorphicDispatcher extends &id:oatpp::data::mapping::type::__class::Collection::PolymorphicDispatcher;.
*/
const bool isCollection;
/**
* polymorphicDispatcher extends &id:oatpp::data::mapping::type::__class::Map::PolymorphicDispatcher;.
*/
const bool isMap;
public:
/**
* Find type interpretation.
* @param names - list of possible interpretation names.
* @return - &l:Type::AbstractInterpretation;. Returns the first interpretation found from the list or NULL if no
* interpretations found.
*/
const AbstractInterpretation* findInterpretation(const std::vector<std::string>& names) const;
/**
* Check if type extends other type.
* @param other
* @return
*/
bool extends(const Type* other) const;
};
template <class T, class Clazz>
template<class Wrapper>
Wrapper ObjectWrapper<T, Clazz>::cast() const {
if(!Wrapper::Class::getType()->extends(m_valueType)) {
if(Wrapper::Class::getType() != __class::Void::getType() && m_valueType != __class::Void::getType()) {
throw std::runtime_error("[oatpp::data::mapping::type::ObjectWrapper::cast()]: Error. Invalid cast "
"from '" + std::string(m_valueType->classId.name) + "' to '" +
std::string(Wrapper::Class::getType()->classId.name) + "'.");
}
}
return Wrapper(std::static_pointer_cast<typename Wrapper::ObjectType>(m_ptr), Wrapper::Class::getType());
}
template <class T, class Clazz>
void ObjectWrapper<T, Clazz>::checkType(const Type* _this, const Type* other) {
if(!_this->extends(other)) {
throw std::runtime_error("[oatpp::data::mapping::type::ObjectWrapper::checkType()]: Error. "
"Type mismatch: stored '" + std::string(_this->classId.name) + "' vs "
"assigned '" + std::string(other->classId.name) + "'.");
}
}
#define OATPP_DEFINE_OBJECT_WRAPPER_DEFAULTS(WRAPPER_NAME, OBJECT_TYPE, OBJECT_CLASS) \
public: \
WRAPPER_NAME(const std::shared_ptr<OBJECT_TYPE>& ptr, const type::Type* const valueType) \
: type::ObjectWrapper<OBJECT_TYPE, OBJECT_CLASS>(ptr, valueType) \
{} \
public: \
\
WRAPPER_NAME() {} \
\
WRAPPER_NAME(std::nullptr_t) {} \
\
WRAPPER_NAME(const std::shared_ptr<OBJECT_TYPE>& ptr) \
: type::ObjectWrapper<OBJECT_TYPE, OBJECT_CLASS>(ptr) \
{} \
\
WRAPPER_NAME(std::shared_ptr<OBJECT_TYPE>&& ptr) \
: type::ObjectWrapper<OBJECT_TYPE, OBJECT_CLASS>(std::forward<std::shared_ptr<OBJECT_TYPE>>(ptr)) \
{} \
\
WRAPPER_NAME(const WRAPPER_NAME& other) \
: type::ObjectWrapper<OBJECT_TYPE, OBJECT_CLASS>(other) \
{} \
\
WRAPPER_NAME(WRAPPER_NAME&& other) \
: type::ObjectWrapper<OBJECT_TYPE, OBJECT_CLASS>(std::forward<WRAPPER_NAME>(other)) \
{} \
\
inline WRAPPER_NAME& operator = (std::nullptr_t) { \
this->m_ptr.reset(); \
return *this; \
} \
\
inline WRAPPER_NAME& operator = (const WRAPPER_NAME& other) { \
this->m_ptr = other.m_ptr; \
return *this; \
} \
\
inline WRAPPER_NAME& operator = (WRAPPER_NAME&& other) { \
this->m_ptr = std::move(other.m_ptr); \
return *this; \
} \
}}}}
namespace std {
template<>
struct hash<oatpp::data::mapping::type::ClassId> {
typedef oatpp::data::mapping::type::ClassId argument_type;
typedef v_uint64 result_type;
result_type operator()(argument_type const& v) const noexcept {
return v.id;
}
};
template<>
struct hash<oatpp::data::mapping::type::Void> {
typedef oatpp::data::mapping::type::Void argument_type;
typedef v_uint64 result_type;
result_type operator()(argument_type const& v) const noexcept {
return (result_type) v.get();
}
};
}
#endif /* oatpp_data_type_Type_hpp */
| vincent-in-black-sesame/oat | src/oatpp/core/data/mapping/type/Type.hpp | C++ | apache-2.0 | 16,106 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#include "UnorderedMap.hpp"
namespace oatpp { namespace data { namespace mapping { namespace type {
namespace __class {
const ClassId AbstractUnorderedMap::CLASS_ID("UnorderedMap");
}
}}}}
| vincent-in-black-sesame/oat | src/oatpp/core/data/mapping/type/UnorderedMap.cpp | C++ | apache-2.0 | 1,188 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef oatpp_data_mapping_type_UnorderedMap_hpp
#define oatpp_data_mapping_type_UnorderedMap_hpp
#include "./Map.hpp"
#include "./Type.hpp"
#include <unordered_map>
#include <initializer_list>
#include <utility>
namespace oatpp { namespace data { namespace mapping { namespace type {
namespace __class {
/**
* Abstract Unordered Map class.
*/
class AbstractUnorderedMap {
public:
/**
* Class Id.
*/
static const ClassId CLASS_ID;
};
template<class Key, class Value>
class UnorderedMap;
}
/**
* `ObjectWrapper` for `std::unordered_map<Key, Value>`
* @tparam Key - Key `ObjectWrapper` type.
* @tparam Value - Value `ObjectWrapper` type.
* @tparam C - Class.
*/
template<class Key, class Value, class C>
class UnorderedMapObjectWrapper : public type::ObjectWrapper<std::unordered_map<Key, Value>, C> {
public:
typedef std::unordered_map<Key, Value> TemplateObjectType;
typedef C TemplateObjectClass;
public:
OATPP_DEFINE_OBJECT_WRAPPER_DEFAULTS(UnorderedMapObjectWrapper, TemplateObjectType, TemplateObjectClass)
UnorderedMapObjectWrapper(std::initializer_list<std::pair<const Key, Value>> ilist)
: type::ObjectWrapper<TemplateObjectType, TemplateObjectClass>(std::make_shared<TemplateObjectType>(ilist))
{}
static UnorderedMapObjectWrapper createShared() {
return std::make_shared<TemplateObjectType>();
}
UnorderedMapObjectWrapper& operator = (std::initializer_list<std::pair<const Key, Value>> ilist) {
this->m_ptr = std::make_shared<TemplateObjectType>(ilist);
return *this;
}
Value& operator[] (const Key& key) const {
return this->m_ptr->operator [] (key);
}
TemplateObjectType& operator*() const {
return this->m_ptr.operator*();
}
};
/**
* Mapping-Enables UnorderedMap<Key, Value>. See &l:UnorderedMapObjectWrapper;.
*/
template<class Key, class Value>
using UnorderedMap = UnorderedMapObjectWrapper<Key, Value, __class::UnorderedMap<Key, Value>>;
namespace __class {
template<class Key, class Value>
class UnorderedMap : public AbstractUnorderedMap {
private:
static Type createType() {
Type::Info info;
info.params.push_back(Key::Class::getType());
info.params.push_back(Value::Class::getType());
info.polymorphicDispatcher =
new typename __class::StandardMap<std::unordered_map<Key, Value>, Key, Value, UnorderedMap>::PolymorphicDispatcher();
info.isMap = true;
return Type(__class::AbstractUnorderedMap::CLASS_ID, info);
}
public:
static Type* getType() {
static Type type = createType();
return &type;
}
};
}
}}}}
#endif // oatpp_data_mapping_type_UnorderedMap_hpp
| vincent-in-black-sesame/oat | src/oatpp/core/data/mapping/type/UnorderedMap.hpp | C++ | apache-2.0 | 3,672 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#include "UnorderedSet.hpp"
namespace oatpp { namespace data { namespace mapping { namespace type {
namespace __class {
const ClassId AbstractUnorderedSet::CLASS_ID("UnorderedSet");
}
}}}} | vincent-in-black-sesame/oat | src/oatpp/core/data/mapping/type/UnorderedSet.cpp | C++ | apache-2.0 | 1,189 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef oatpp_data_mapping_type_UnorderedSet_hpp
#define oatpp_data_mapping_type_UnorderedSet_hpp
#include "./Collection.hpp"
#include "./Type.hpp"
#include <unordered_set>
#include <initializer_list>
namespace oatpp { namespace data { namespace mapping { namespace type {
namespace __class {
/**
* Abstract Unordered Set class.
*/
class AbstractUnorderedSet {
public:
/**
* Class Id.
*/
static const ClassId CLASS_ID;
};
template<class T>
class UnorderedSet;
}
/**
* `ObjectWrapper` over `std::unordered_set<T>`
* @tparam T - Key `ObjectWrapper` type.
* @tparam C - Class.
*/
template<class T, class C>
class UnorderedSetObjectWrapper : public type::ObjectWrapper<std::unordered_set<T>, C> {
public:
typedef std::unordered_set<T> TemplateObjectType;
typedef C TemplateObjectClass;
public:
OATPP_DEFINE_OBJECT_WRAPPER_DEFAULTS(UnorderedSetObjectWrapper, TemplateObjectType, TemplateObjectClass)
UnorderedSetObjectWrapper(std::initializer_list<T> ilist)
: type::ObjectWrapper<TemplateObjectType, TemplateObjectClass>(std::make_shared<TemplateObjectType>(ilist))
{}
static UnorderedSetObjectWrapper createShared() {
return std::make_shared<TemplateObjectType>();
}
UnorderedSetObjectWrapper& operator = (std::initializer_list<T> ilist) {
this->m_ptr = std::make_shared<TemplateObjectType>(ilist);
return *this;
}
bool operator[] (const T& key) const {
if(this->m_ptr) {
auto it = this->m_ptr->find(key);
return it != this->m_ptr->end();
}
return false;
}
TemplateObjectType& operator*() const {
return this->m_ptr.operator*();
}
};
/**
* Mapping-Enabled UnorderedSet. See &l:UnorderedSetObjectWrapper;.
*/
template<class T>
using UnorderedSet = UnorderedSetObjectWrapper<T, __class::UnorderedSet<T>>;
typedef UnorderedSet<Void> AbstractUnorderedSet;
namespace __class {
template<class T>
class UnorderedSet : public AbstractUnorderedSet {
private:
static Type createType() {
Type::Info info;
info.params.push_back(T::Class::getType());
info.polymorphicDispatcher = new typename StandardCollection<std::unordered_set<T>, T, UnorderedSet>::PolymorphicDispatcher();
info.isCollection = true;
return Type(__class::AbstractUnorderedSet::CLASS_ID, info);
}
public:
static Type* getType() {
static Type type = createType();
return &type;
}
};
}
}}}}
#endif // oatpp_data_mapping_type_UnorderedSet_hpp
| vincent-in-black-sesame/oat | src/oatpp/core/data/mapping/type/UnorderedSet.hpp | C++ | apache-2.0 | 3,462 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#include "Vector.hpp"
namespace oatpp { namespace data { namespace mapping { namespace type {
namespace __class {
const ClassId AbstractVector::CLASS_ID("Vector");
}
}}}} | vincent-in-black-sesame/oat | src/oatpp/core/data/mapping/type/Vector.cpp | C++ | apache-2.0 | 1,171 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef oatpp_data_mapping_type_Vector_hpp
#define oatpp_data_mapping_type_Vector_hpp
#include "./Collection.hpp"
#include "./Type.hpp"
#include <vector>
#include <initializer_list>
namespace oatpp { namespace data { namespace mapping { namespace type {
namespace __class {
/**
* Abstract Vector Class.
*/
class AbstractVector {
public:
/**
* Class Id.
*/
static const ClassId CLASS_ID;
};
template<class T>
class Vector;
}
/**
* `ObjectWrapper` over `std::vector<T>`.
* @tparam T - Item `ObjectWrapper` type.
* @tparam C - Class.
*/
template<class T, class C>
class VectorObjectWrapper : public type::ObjectWrapper<std::vector<T>, C> {
public:
typedef std::vector<T> TemplateObjectType;
typedef C TemplateObjectClass;
public:
OATPP_DEFINE_OBJECT_WRAPPER_DEFAULTS(VectorObjectWrapper, TemplateObjectType, TemplateObjectClass)
VectorObjectWrapper(std::initializer_list<T> ilist)
: type::ObjectWrapper<TemplateObjectType, TemplateObjectClass>(std::make_shared<TemplateObjectType>(ilist))
{}
static VectorObjectWrapper createShared() {
return std::make_shared<TemplateObjectType>();
}
VectorObjectWrapper& operator = (std::initializer_list<T> ilist) {
this->m_ptr = std::make_shared<TemplateObjectType>(ilist);
return *this;
}
T& operator[] (v_buff_usize index) const {
return this->m_ptr->operator [] (index);
}
TemplateObjectType& operator*() const {
return this->m_ptr.operator*();
}
};
/**
* Mapping-enabled Vector. See &l:VectorObjectWrapper;.
*/
template<class T>
using Vector = VectorObjectWrapper<T, __class::Vector<T>>;
typedef Vector<Void> AbstractVector;
namespace __class {
template<class T>
class Vector : public AbstractVector {
private:
static Type createType() {
Type::Info info;
info.params.push_back(T::Class::getType());
info.polymorphicDispatcher = new typename StandardCollection<std::vector<T>, T, Vector>::PolymorphicDispatcher();
info.isCollection = true;
return Type(__class::AbstractVector::CLASS_ID, info);
}
public:
static Type* getType() {
static Type type = createType();
return &type;
}
};
}
}}}}
#endif // oatpp_data_mapping_type_Vector_hpp
| vincent-in-black-sesame/oat | src/oatpp/core/data/mapping/type/Vector.hpp | C++ | apache-2.0 | 3,252 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#include "File.hpp"
#include "oatpp/core/data/stream/FileStream.hpp"
namespace oatpp { namespace data { namespace resource {
oatpp::String File::concatDirAndName(const oatpp::String& dir, const oatpp::String& filename) {
if(dir && dir->size() > 0) {
auto lastChar = dir->data()[dir->size() - 1];
if(lastChar != '/' && lastChar != '\\') {
return dir + "/" + filename;
}
return dir + filename;
}
return filename;
}
File::File(const oatpp::String& fullFileName)
: m_handle(std::make_shared<FileHandle>(fullFileName))
{}
File::File(const oatpp::String& tmpDirectory, const oatpp::String& tmpFileName)
: m_handle(std::make_shared<FileHandle>(concatDirAndName(tmpDirectory, tmpFileName)))
{}
std::shared_ptr<data::stream::OutputStream> File::openOutputStream() {
if(m_handle) {
return std::make_shared<data::stream::FileOutputStream>(m_handle->fileName->c_str(), "wb", m_handle);
}
throw std::runtime_error("[oatpp::data::resource::File::openOutputStream()]: Error. FileHandle is NOT initialized.");
}
std::shared_ptr<data::stream::InputStream> File::openInputStream() {
if(m_handle) {
return std::make_shared<data::stream::FileInputStream>(m_handle->fileName->c_str(), m_handle);
}
throw std::runtime_error("[oatpp::data::resource::File::openInputStream()]: Error. FileHandle is NOT initialized.");
}
oatpp::String File::getInMemoryData() {
return nullptr;
}
v_int64 File::getKnownSize() {
return -1;
}
oatpp::String File::getLocation() {
if(m_handle) {
return m_handle->fileName;
}
return nullptr;
}
}}}
| vincent-in-black-sesame/oat | src/oatpp/core/data/resource/File.cpp | C++ | apache-2.0 | 2,573 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef oatpp_data_resource_File_hpp
#define oatpp_data_resource_File_hpp
#include "./Resource.hpp"
#include "oatpp/core/data/stream/Stream.hpp"
namespace oatpp { namespace data { namespace resource {
/**
* File.
* @extends - &id:oatpp::data::Resource;.
*/
class File : public Resource {
private:
struct FileHandle {
oatpp::String fileName;
FileHandle(const oatpp::String& fullFileName)
: fileName(fullFileName)
{}
};
public:
static oatpp::String concatDirAndName(const oatpp::String& dir, const oatpp::String& filename);
private:
std::shared_ptr<FileHandle> m_handle;
public:
/**
* Default constructor.
*/
File() = default;
/**
* Constructor.
* @param fullFilename
*/
File(const oatpp::String& fullFilename);
/**
* Constructor.
* @param directory
* @param filename
*/
File(const oatpp::String& directory, const oatpp::String& filename);
/**
* Open output stream to a file. <br>
* *Note: stream also captures file-handle. The file object won't be deleted until the stream is deleted.*
* @return - `std::shared_ptr` to &id:oatpp::data::stream::OutputStream;.
*/
std::shared_ptr<data::stream::OutputStream> openOutputStream() override;
/**
* Open input stream to a temporary file. <br>
* *Note: stream also captures file-handle. The file won't be deleted until the stream is deleted.*
* @return - `std::shared_ptr` &id:oatpp::data::stream::InputStream;.
*/
std::shared_ptr<data::stream::InputStream> openInputStream() override;
/**
* Not applicable.
* @return - always returns `nullptr`.
*/
oatpp::String getInMemoryData() override;
/**
* Not applicable.
* @return - always returns `-1`.
*/
v_int64 getKnownSize() override;
/**
* Get location where temporary data is stored.
* @return - `&id:oatpp::String;`.
*/
oatpp::String getLocation() override;
};
}}}
#endif //oatpp_data_resource_File_hpp
| vincent-in-black-sesame/oat | src/oatpp/core/data/resource/File.hpp | C++ | apache-2.0 | 2,949 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#include "InMemoryData.hpp"
namespace oatpp { namespace data { namespace resource {
InMemoryData::OutputDataHandle::~OutputDataHandle() {
dataHandle->data = data + stream->toString();
}
InMemoryData::InMemoryData(const oatpp::String& data)
: m_handle(std::make_shared<DataHandle>(data))
{}
std::shared_ptr<data::stream::OutputStream> InMemoryData::openOutputStream() {
auto outputDataHandle = std::make_shared<OutputDataHandle>();
if(!m_handle) {
m_handle = std::make_shared<DataHandle>("");
}
if(!m_handle->data){
m_handle->data = "";
}
outputDataHandle->dataHandle = m_handle;
outputDataHandle->data = m_handle->data;
auto stream = std::make_shared<data::stream::BufferOutputStream>(1024, outputDataHandle);
outputDataHandle->stream = stream.get();
return stream;
}
std::shared_ptr<data::stream::InputStream> InMemoryData::openInputStream() {
if(!m_handle) {
m_handle = std::make_shared<DataHandle>("");
}
if(!m_handle->data){
m_handle->data = "";
}
return std::make_shared<data::stream::BufferInputStream>(m_handle->data, m_handle);
}
oatpp::String InMemoryData::getInMemoryData() {
if(m_handle && m_handle->data) {
return m_handle->data;
}
return nullptr;
}
v_int64 InMemoryData::getKnownSize() {
if(m_handle && m_handle->data) {
return m_handle->data->size();
}
return 0;
}
oatpp::String InMemoryData::getLocation() {
return nullptr;
}
}}}
| vincent-in-black-sesame/oat | src/oatpp/core/data/resource/InMemoryData.cpp | C++ | apache-2.0 | 2,423 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef oatpp_data_resource_InMemoryData_hpp
#define oatpp_data_resource_InMemoryData_hpp
#include "./Resource.hpp"
#include "oatpp/core/data/stream/BufferStream.hpp"
namespace oatpp { namespace data { namespace resource {
class InMemoryData : public Resource {
private:
struct DataHandle {
oatpp::String data;
DataHandle(const oatpp::String& pData)
: data(pData)
{}
};
struct OutputDataHandle {
std::shared_ptr<DataHandle> dataHandle;
oatpp::String data;
data::stream::BufferOutputStream* stream;
~OutputDataHandle();
};
private:
std::shared_ptr<DataHandle> m_handle;
public:
/**
* Default constructor.
*/
InMemoryData() = default;
/**
* Constructor.
* @param fullInMemoryDataname
*/
InMemoryData(const oatpp::String& data);
/**
* Open output stream to an InMemoryData. <br>
* NOT thread-safe. <br>
* *Note: data is committed once stream is closed.* <br>
* *Note: stream also captures data-handle. The data won't be deleted until the stream is deleted.*
* @return - `std::shared_ptr` to &id:oatpp::data::stream::OutputStream;.
*/
std::shared_ptr<data::stream::OutputStream> openOutputStream() override;
/**
* Open input stream to an InMemoryData. <br>
* NOT thread-safe. <br>
* *Note: once the stream is open no subsequent writes through the output stream won't affect currently opened input streams.* <br>
* *Note: stream also captures file-handle. The data won't be deleted until the stream is deleted.*
* @return - `std::shared_ptr` &id:oatpp::data::stream::InputStream;.
*/
std::shared_ptr<data::stream::InputStream> openInputStream() override;
/**
* Get in-memory-data.
* @return - always returns `nullptr`.
*/
oatpp::String getInMemoryData() override;
/**
* Get size of an in-memory-data.
* @return - size of the data in bytes.
*/
v_int64 getKnownSize() override;
/**
* Not applicable.
* @return - always returns `nullptr`.
*/
oatpp::String getLocation() override;
};
}}}
#endif //oatpp_data_resource_InMemoryData_hpp
| vincent-in-black-sesame/oat | src/oatpp/core/data/resource/InMemoryData.hpp | C++ | apache-2.0 | 3,093 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef oatpp_data_resource_Resource_hpp
#define oatpp_data_resource_Resource_hpp
#include "oatpp/core/data/stream/Stream.hpp"
namespace oatpp { namespace data { namespace resource {
/**
* Abstract data resource
*/
class Resource : public oatpp::base::Countable {
public:
/**
* virtual destructor.
*/
virtual ~Resource() = default;
/**
* Open output stream.
* @return
*/
virtual std::shared_ptr<data::stream::OutputStream> openOutputStream() = 0;
/**
* Open input stream.
* @return
*/
virtual std::shared_ptr<data::stream::InputStream> openInputStream() = 0;
/**
* Get in-memory data if applicable.
* @return - `&id:oatpp::String;` or `nullptr` if not applicable.
*/
virtual oatpp::String getInMemoryData() = 0;
/**
* Get known data size if applicable.
* @return - known size of the data. `-1` - if size is unknown.
*/
virtual v_int64 getKnownSize() = 0;
/**
* Get resource location if applicable. <br>
* location can be for example a file name.
* @return - `&id:oatpp::String;` or `nullptr` if not applicable.
*/
virtual oatpp::String getLocation() = 0;
};
}}}
#endif //oatpp_data_resource_Resource_hpp
| vincent-in-black-sesame/oat | src/oatpp/core/data/resource/Resource.hpp | C++ | apache-2.0 | 2,192 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#include "TemporaryFile.hpp"
#include "./File.hpp"
#include "oatpp/core/data/stream/FileStream.hpp"
#include "oatpp/core/data/stream/BufferStream.hpp"
#include "oatpp/encoding/Hex.hpp"
#include "oatpp/core/utils/Random.hpp"
namespace oatpp { namespace data { namespace resource {
TemporaryFile::FileHandle::~FileHandle() {
if(fileName) {
std::remove(fileName->c_str());
}
}
oatpp::String TemporaryFile::constructRandomFilename(const oatpp::String &dir, v_int32 randomWordSizeBytes, const oatpp::String &extension) {
std::unique_ptr<v_char8[]> buff(new v_char8[randomWordSizeBytes]);
utils::random::Random::randomBytes(buff.get(), randomWordSizeBytes);
data::stream::BufferOutputStream s(randomWordSizeBytes * 2 + 4);
encoding::Hex::encode(&s, buff.get(), randomWordSizeBytes, encoding::Hex::ALPHABET_LOWER);
if (extension->at(0) != '.') {
s << ".";
}
s << extension;
return File::concatDirAndName(dir, s.toString());
}
TemporaryFile::TemporaryFile(const oatpp::String& tmpDirectory, v_int32 randomWordSizeBytes)
: m_handle(std::make_shared<FileHandle>(constructRandomFilename(tmpDirectory, randomWordSizeBytes, "tmp")))
{}
TemporaryFile::TemporaryFile(const oatpp::String& tmpDirectory, const oatpp::String& tmpFileName)
: m_handle(std::make_shared<FileHandle>(File::concatDirAndName(tmpDirectory, tmpFileName)))
{}
TemporaryFile::TemporaryFile(const oatpp::String& tmpDirectory, v_int32 randomWordSizeBytes, const oatpp::String& extension)
: m_handle(std::make_shared<FileHandle>(constructRandomFilename(tmpDirectory, randomWordSizeBytes, extension)))
{}
std::shared_ptr<data::stream::OutputStream> TemporaryFile::openOutputStream() {
if(m_handle) {
return std::make_shared<data::stream::FileOutputStream>(m_handle->fileName->c_str(), "wb", m_handle);
}
throw std::runtime_error("[oatpp::data::resource::TemporaryFile::openOutputStream()]: Error. FileHandle is NOT initialized.");
}
std::shared_ptr<data::stream::InputStream> TemporaryFile::openInputStream() {
if(m_handle) {
return std::make_shared<data::stream::FileInputStream>(m_handle->fileName->c_str(), m_handle);
}
throw std::runtime_error("[oatpp::data::resource::TemporaryFile::openInputStream()]: Error. FileHandle is NOT initialized.");
}
oatpp::String TemporaryFile::getInMemoryData() {
return nullptr;
}
v_int64 TemporaryFile::getKnownSize() {
return -1;
}
oatpp::String TemporaryFile::getLocation() {
if(m_handle) {
return m_handle->fileName;
}
return nullptr;
}
bool TemporaryFile::moveFile(const oatpp::String& fullFileName) {
if(m_handle) {
return std::rename(m_handle->fileName->c_str(), fullFileName->c_str()) == 0;
}
return false;
}
}}}
| vincent-in-black-sesame/oat | src/oatpp/core/data/resource/TemporaryFile.cpp | C++ | apache-2.0 | 3,701 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef oatpp_data_resource_TemporaryFile_hpp
#define oatpp_data_resource_TemporaryFile_hpp
#include "./Resource.hpp"
#include "oatpp/core/Types.hpp"
namespace oatpp { namespace data { namespace resource {
/**
* Temporary file - the file which gets deleted when the destructor is called
* (more precisely when all copies of the same `TemporaryFile` object deleted). <br>
* The `TemporaryFile` object internally stores a `shared_ptr` to a file handle.
* When file handle deleted it also deletes the underlying file. <br>
* Thus it's safe to copy `TemporaryFile` object and you may treat `TemporaryFile` object
* as a shared_ptr to a temporary file. <br>
* @extends - &id:oatpp::data::Resource;.
*/
class TemporaryFile : public Resource {
private:
/*
* Shared handle.
* File is deleted on handle destroy.
*/
struct FileHandle {
oatpp::String fileName;
FileHandle(const oatpp::String& fullFileName)
: fileName(fullFileName)
{}
~FileHandle();
};
private:
static oatpp::String constructRandomFilename(const oatpp::String &dir, v_int32 randomWordSizeBytes, const oatpp::String &extension);
private:
std::shared_ptr<FileHandle> m_handle;
public:
/**
* Default constructor.
*/
TemporaryFile() = default;
/**
* Constructor. <br>
* Create temporary file with a random name in the `tmpDirectory`. <br>
* The actual file will be created only after first write to that file. <br>
* Example of the generated random file name: `f7c6ecd44024ff31.tmp`.
* @param tmpDirectory - directory where to create a temporary file.
* @param randomWordSizeBytes - number of random bytes to generate file name.
*/
TemporaryFile(const oatpp::String& tmpDirectory, v_int32 randomWordSizeBytes = 8);
/**
* Constructor.<br>
* Create temporary file with the `tmpFileName` name in the `tmpDirectory`. <br>
* @param tmpDirectory - directory where to create a temporary file.
* @param tmpFileName - predefined name for the temporary file.
*/
TemporaryFile(const oatpp::String& tmpDirectory, const oatpp::String& tmpFileName);
/**
* Constructor. <br>
* Create temporary file with a random name and specified extension in the `tmpDirectory`. <br>
* The actual file will be created only after first write to that file. <br>
* Example of the generated random file name: `f7c6ecd44024ff31.txt`.
* @param tmpDirectory - directory where to create a temporary file.
* @param randomWordSizeBytes - number of random bytes to generate file name.
* @param extension - extension of the temporary file, e.g. txt or .txt
*/
TemporaryFile(const oatpp::String& tmpDirectory, v_int32 randomWordSizeBytes, const oatpp::String& extension);
/**
* Open output stream to a temporary file. <br>
* *Note: stream also captures file-handle. The temporary file won't be deleted until the stream is deleted.*
* @return - `std::shared_ptr` to &id:oatpp::data::stream::OutputStream;.
*/
std::shared_ptr<data::stream::OutputStream> openOutputStream() override;
/**
* Open input stream to a temporary file. <br>
* *Note: stream also captures file-handle. The temporary file won't be deleted until the stream is deleted.*
* @return - `std::shared_ptr` &id:oatpp::data::stream::InputStream;.
*/
std::shared_ptr<data::stream::InputStream> openInputStream() override;
/**
* Not applicable.
* @return - always returns `nullptr`.
*/
oatpp::String getInMemoryData() override;
/**
* Not applicable.
* @return - always returns `-1`.
*/
v_int64 getKnownSize() override;
/**
* Get location where temporary data is stored.
* @return - `&id:oatpp::String;`.
*/
oatpp::String getLocation() override;
/**
* Move payload to a different file. <br>
* @param fullFileName - full-file-name. Note: all the parent folders must exist.
* @return - `true` - file was successfully moved, `false` - otherwise.
*/
bool moveFile(const oatpp::String& fullFileName);
};
}}}
#endif //oatpp_data_resource_TemporaryFile_hpp
| vincent-in-black-sesame/oat | src/oatpp/core/data/resource/TemporaryFile.hpp | C++ | apache-2.0 | 5,054 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef oatpp_data_share_LazyStringMap_hpp
#define oatpp_data_share_LazyStringMap_hpp
#include "./MemoryLabel.hpp"
#include "oatpp/core/concurrency/SpinLock.hpp"
#include <unordered_map>
namespace oatpp { namespace data { namespace share {
/**
* Lazy String Map keeps keys, and values as memory label.
* Once value is requested by user, the new memory block is allocated and value is copied to be stored permanently.
* @tparam Key - one of: &id:oatpp::data::share::MemoryLabel;, &id:oatpp::data::share::StringKeyLabel;, &id:oatpp::data::share::StringKeyLabelCI;,
* &id:oatpp::data::share::StringKeyLabelCI;.
*/
template<typename Key, typename MapType>
class LazyStringMapTemplate {
public:
typedef oatpp::data::mapping::type::String String;
private:
mutable concurrency::SpinLock m_lock;
mutable bool m_fullyInitialized;
MapType m_map;
public:
/**
* Constructor.
*/
LazyStringMapTemplate()
: m_fullyInitialized(true)
{}
/**
* Copy-constructor.
* @param other
*/
LazyStringMapTemplate(const LazyStringMapTemplate& other) {
std::lock_guard<concurrency::SpinLock> otherLock(other.m_lock);
m_fullyInitialized = other.m_fullyInitialized;
m_map = MapType(other.m_map);
}
/**
* Move constructor.
* @param other
*/
LazyStringMapTemplate(LazyStringMapTemplate&& other) {
std::lock_guard<concurrency::SpinLock> otherLock(other.m_lock);
m_fullyInitialized = other.m_fullyInitialized;
m_map = std::move(other.m_map);
}
LazyStringMapTemplate& operator = (const LazyStringMapTemplate& other) {
if(this != &other) {
std::lock_guard<concurrency::SpinLock> thisLock(m_lock);
std::lock_guard<concurrency::SpinLock> otherLock(other.m_lock);
m_fullyInitialized = other.m_fullyInitialized;
m_map = MapType(other.m_map);
}
return *this;
}
LazyStringMapTemplate& operator = (LazyStringMapTemplate&& other) {
if(this != &other) {
std::lock_guard<concurrency::SpinLock> thisLock(m_lock);
std::lock_guard<concurrency::SpinLock> otherLock(other.m_lock);
m_fullyInitialized = other.m_fullyInitialized;
m_map = std::move(other.m_map);
}
return *this;
}
/**
* Put value to map.
* @param key
* @param value
*/
void put(const Key& key, const StringKeyLabel& value) {
std::lock_guard<concurrency::SpinLock> lock(m_lock);
m_map.insert({key, value});
m_fullyInitialized = false;
}
/**
* Put value to map. Not thread-safe.
* @param key
* @param value
*/
void put_LockFree(const Key& key, const StringKeyLabel& value) {
m_map.insert({key, value});
m_fullyInitialized = false;
}
/**
* Put value to map if not already exists.
* @param key
* @param value
* @return
*/
bool putIfNotExists(const Key& key, const StringKeyLabel& value) {
std::lock_guard<concurrency::SpinLock> lock(m_lock);
auto it = m_map.find(key);
if(it == m_map.end()) {
m_map.insert({key, value});
m_fullyInitialized = false;
return true;
}
return false;
}
/**
* Put value to map if not already exists. Not thread-safe.
* @param key
* @param value
* @return
*/
bool putIfNotExists_LockFree(const Key& key, const StringKeyLabel& value) {
auto it = m_map.find(key);
if(it == m_map.end()) {
m_map.insert({key, value});
m_fullyInitialized = false;
return true;
}
return false;
}
/**
* Erases all occurrences of key and replaces them with a new entry
* @param key
* @param value
* @return - true if an entry was replaced, false if entry was only inserted.
*/
bool putOrReplace(const Key& key, const StringKeyLabel& value) {
std::lock_guard<concurrency::SpinLock> lock(m_lock);
bool needsErase = m_map.find(key) != m_map.end();
if (needsErase) {
m_map.erase(key);
}
m_map.insert({key, value});
m_fullyInitialized = false;
return needsErase;
}
/**
* Erases all occurrences of key and replaces them with a new entry. Not thread-safe.
* @param key
* @param value
* @return - `true` if an entry was replaced, `false` if entry was only inserted.
*/
bool putOrReplace_LockFree(const Key& key, const StringKeyLabel& value) {
bool needsErase = m_map.find(key) != m_map.end();
if (needsErase) {
m_map.erase(key);
}
m_map.insert({key, value});
m_fullyInitialized = false;
return needsErase;
}
/**
* Get value as &id:oatpp::String;.
* @param key
* @return
*/
String get(const Key& key) const {
std::lock_guard<concurrency::SpinLock> lock(m_lock);
auto it = m_map.find(key);
if(it != m_map.end()) {
it->second.captureToOwnMemory();
return it->second.getMemoryHandle();
}
return nullptr;
}
/**
* Get value as a memory label.
* @tparam T - one of: &id:oatpp::data::share::MemoryLabel;, &id:oatpp::data::share::StringKeyLabel;, &id:oatpp::data::share::StringKeyLabelCI;.
* @param key
* @return
*/
template<class T>
T getAsMemoryLabel(const Key& key) const {
std::lock_guard<concurrency::SpinLock> lock(m_lock);
auto it = m_map.find(key);
if(it != m_map.end()) {
it->second.captureToOwnMemory();
const auto& label = it->second;
return T(label.getMemoryHandle(), (const char*) label.getData(), label.getSize());
}
return T(nullptr, nullptr, 0);
}
/**
* Get value as a memory label without allocating memory for value.
* @tparam T - one of: &id:oatpp::data::share::MemoryLabel;, &id:oatpp::data::share::StringKeyLabel;, &id:oatpp::data::share::StringKeyLabelCI;,
* * &id:oatpp::data::share::StringKeyLabelCI;.
* @param key
* @return
*/
template<class T>
T getAsMemoryLabel_Unsafe(const Key& key) const {
std::lock_guard<concurrency::SpinLock> lock(m_lock);
auto it = m_map.find(key);
if(it != m_map.end()) {
const auto& label = it->second;
return T(label.getMemoryHandle(), (const char*)label.getData(), label.getSize());
}
return T(nullptr, nullptr, 0);
}
/**
* Get map of all values.
* @return
*/
const MapType& getAll() const {
std::lock_guard<concurrency::SpinLock> lock(m_lock);
if(!m_fullyInitialized) {
for(auto& pair : m_map) {
pair.first.captureToOwnMemory();
pair.second.captureToOwnMemory();
}
m_fullyInitialized = true;
}
return m_map;
}
/**
* Get map of all values without allocating memory for those keys/values.
* @return
*/
const MapType& getAll_Unsafe() const {
return m_map;
}
/**
* Get number of entries in the map.
* @return
*/
v_int32 getSize() const {
std::lock_guard<concurrency::SpinLock> lock(m_lock);
return (v_int32) m_map.size();
}
};
/**
* Convenience template for &l:LazyStringMapTemplate;. Based on `std::unordered_map`.
*/
template<typename Key, typename Value = StringKeyLabel>
using LazyStringMap = LazyStringMapTemplate<Key, std::unordered_map<Key, Value>>;
/**
* Convenience template for &l:LazyStringMapTemplate;. Based on `std::unordered_map`.
*/
template<typename Key, typename Value = StringKeyLabel>
using LazyStringMultimap = LazyStringMapTemplate<Key, std::unordered_multimap<Key, Value>>;
}}}
#endif //oatpp_data_share_LazyStringMap_hpp
| vincent-in-black-sesame/oat | src/oatpp/core/data/share/LazyStringMap.hpp | C++ | apache-2.0 | 8,385 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#include "MemoryLabel.hpp"
#include <cstring>
namespace oatpp { namespace data { namespace share {
MemoryLabel::MemoryLabel(const std::shared_ptr<std::string>& memHandle, const void* data, v_buff_size size)
: m_memoryHandle(memHandle)
, m_data(data)
, m_size(size)
{}
StringKeyLabel::StringKeyLabel(const std::shared_ptr<std::string>& memHandle, const char* data, v_buff_size size)
: oatpp::data::share::MemoryLabel(memHandle, data, size)
{}
StringKeyLabel::StringKeyLabel(const char* constText)
: oatpp::data::share::MemoryLabel(nullptr, constText, std::strlen(constText))
{}
StringKeyLabel::StringKeyLabel(const String& str)
: oatpp::data::share::MemoryLabel(str.getPtr(), str->data(), str->size())
{}
StringKeyLabelCI::StringKeyLabelCI(const std::shared_ptr<std::string>& memHandle, const char* data, v_buff_size size)
: oatpp::data::share::MemoryLabel(memHandle, data, size)
{}
StringKeyLabelCI::StringKeyLabelCI(const char* constText)
: oatpp::data::share::MemoryLabel(nullptr, constText, std::strlen(constText))
{}
StringKeyLabelCI::StringKeyLabelCI(const String& str)
: oatpp::data::share::MemoryLabel(str.getPtr(), str->data(), str->size())
{}
}}}
| vincent-in-black-sesame/oat | src/oatpp/core/data/share/MemoryLabel.cpp | C++ | apache-2.0 | 2,190 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef oatpp_data_share_MemoryLabel_hpp
#define oatpp_data_share_MemoryLabel_hpp
#include "oatpp/core/data/mapping/type/Primitive.hpp"
#include "oatpp/core/utils/String.hpp"
#include <cstring>
#include <memory>
namespace oatpp { namespace data { namespace share {
/**
* MemoryLabel represent a part of the whole memory buffer refered by handle.
* Advantage of MemoryLabel use is that you may just "label" some data instead of allocating buffer for it's copy.
* You may allocate separate buffer for data copy later once you need it.
*/
class MemoryLabel {
public:
typedef oatpp::data::mapping::type::String String;
protected:
mutable std::shared_ptr<std::string> m_memoryHandle;
mutable const void* m_data;
v_buff_size m_size;
public:
/**
* Default constructor. Null MemoryLabel.
*/
MemoryLabel()
: m_memoryHandle(nullptr)
, m_data(nullptr)
, m_size(0)
{}
/**
* nullptr constructor.
*/
MemoryLabel(std::nullptr_t)
: m_memoryHandle(nullptr)
, m_data(nullptr)
, m_size(0)
{}
/**
* Constructor.
* @param ptr
*/
MemoryLabel(const std::shared_ptr<std::string>& ptr) :
MemoryLabel(
ptr,
ptr ? ptr->data() : nullptr,
ptr ? (v_buff_size) ptr->size() : 0
)
{}
/**
* Constructor.
* @param memHandle - memory handle. `std::shared_ptr` to buffer pointed by a memory label.
* @param data - pointer to data.
* @param size - size of the data in bytes.
*/
MemoryLabel(const std::shared_ptr<std::string>& memHandle, const void* data, v_buff_size size);
/**
* Get pointer to labeled data.
* @return - pointer to data.
*/
const void* getData() const {
return m_data;
}
/**
* Get data size.
* @return - size of the data.
*/
v_buff_size getSize() const {
return m_size;
}
/**
* Get memory handle which this memory label holds.
* @return - `std::shared_ptr` to `std::string`.
*/
std::shared_ptr<std::string> getMemoryHandle() const {
return m_memoryHandle;
}
/**
* Capture data referenced by memory label to its own memory.
*/
void captureToOwnMemory() const {
if(!m_memoryHandle || m_memoryHandle->data() != (const char*)m_data || m_memoryHandle->size() != m_size) {
m_memoryHandle = std::make_shared<std::string>((const char*) m_data, m_size);
m_data = (p_char8) m_memoryHandle->data();
}
}
/**
* Check if labeled data equals to data specified.
* Data is compared using &id:oatpp::urils::String::compare;.
* @param data - data to compare with labeled data.
* @return - `true` if equals.
*/
bool equals(const char* data) const {
auto len = data != nullptr ? std::strlen(data) : 0;
return utils::String::compare(m_data, m_size, data, len) == 0;
}
/**
* Check if labeled data equals to data specified.
* Data is compared using &id:oatpp::urils::String::compare;.
* @param data - data to compare with labeled data.
* @param size - data size.
* @return - `true` if equals.
*/
bool equals(const void* data, v_buff_size size) const {
return utils::String::compare(m_data, m_size, data, size) == 0;
}
/**
* Create oatpp::String from memory label
* @return oatpp::String(data, size)
*/
String toString() const {
return String((const char*) m_data, m_size);
}
/**
* Create std::string from memory label
* @return std::string(data, size)
*/
std::string std_str() const {
return std::string((const char*) m_data, m_size);
}
inline bool operator==(std::nullptr_t) const {
return m_data == nullptr;
}
inline bool operator!=(std::nullptr_t) const {
return m_data != nullptr;
}
inline explicit operator bool() const {
return m_data != nullptr;
}
};
/**
* MemoryLabel which can be used as a key in unordered_map
*/
class StringKeyLabel : public MemoryLabel {
public:
StringKeyLabel() : MemoryLabel() {};
StringKeyLabel(std::nullptr_t) : MemoryLabel() {}
/**
* Constructor.
* @param ptr
*/
StringKeyLabel(const std::shared_ptr<std::string>& ptr) : MemoryLabel(ptr) {}
StringKeyLabel(const std::shared_ptr<std::string>& memoryHandle, const char* data, v_buff_size size);
StringKeyLabel(const char* constText);
StringKeyLabel(const String& str);
inline bool operator==(std::nullptr_t) const {
return m_data == nullptr;
}
inline bool operator!=(std::nullptr_t) const {
return m_data != nullptr;
}
inline bool operator==(const char* str) const {
return equals(str);
}
inline bool operator!=(const char* str) const {
return !operator==(str);
}
inline bool operator==(const String& str) const {
if(m_data == nullptr) return str == nullptr;
if(str == nullptr) return false;
return equals(str->data(), str->size());
}
inline bool operator!=(const String& str) const {
return !operator==(str);
}
inline bool operator==(const StringKeyLabel &other) const {
return utils::String::compare(m_data, m_size, other.m_data, other.m_size) == 0;
}
inline bool operator!=(const StringKeyLabel &other) const {
return !operator==(other);
}
inline bool operator < (const StringKeyLabel &other) const {
return utils::String::compare(m_data, m_size, other.m_data, other.m_size) < 0;
}
inline bool operator > (const StringKeyLabel &other) const {
return utils::String::compare(m_data, m_size, other.m_data, other.m_size) > 0;
}
};
/**
* MemoryLabel which can be used as a case-insensitive key in unordered_map
*/
class StringKeyLabelCI : public MemoryLabel {
public:
StringKeyLabelCI() : MemoryLabel() {};
StringKeyLabelCI(std::nullptr_t) : MemoryLabel() {}
StringKeyLabelCI(const std::shared_ptr<std::string>& ptr) : MemoryLabel(ptr) {}
StringKeyLabelCI(const std::shared_ptr<std::string>& memoryHandle, const char* data, v_buff_size size);
StringKeyLabelCI(const char* constText);
StringKeyLabelCI(const String& str);
inline bool operator==(std::nullptr_t) const {
return m_data == nullptr;
}
inline bool operator!=(std::nullptr_t) const {
return m_data != nullptr;
}
inline bool operator==(const char* str) const {
auto len = str != nullptr ? std::strlen(str) : 0;
return utils::String::compareCI_ASCII(m_data, m_size, str, len) == 0;
}
inline bool operator!=(const char* str) const {
return !operator==(str);
}
inline bool operator==(const String& str) const {
if(m_data == nullptr) return str == nullptr;
if(str == nullptr) return false;
return utils::String::compareCI_ASCII(m_data, m_size, str->data(), str->size()) == 0;
}
inline bool operator!=(const String& str) const {
return !operator==(str);
}
inline bool operator==(const StringKeyLabelCI &other) const {
return utils::String::compareCI_ASCII(m_data, m_size, other.m_data, other.m_size) == 0;
}
inline bool operator!=(const StringKeyLabelCI &other) const {
return !operator==(other);
}
inline bool operator < (const StringKeyLabelCI &other) const {
return utils::String::compareCI_ASCII(m_data, m_size, other.m_data, other.m_size) < 0;
}
inline bool operator > (const StringKeyLabelCI &other) const {
return utils::String::compareCI_ASCII(m_data, m_size, other.m_data, other.m_size) > 0;
}
};
}}}
namespace std {
template<>
struct hash<oatpp::data::share::StringKeyLabel> {
typedef oatpp::data::share::StringKeyLabel argument_type;
typedef v_uint64 result_type;
result_type operator()(oatpp::data::share::StringKeyLabel const& s) const noexcept {
auto data = (p_char8) s.getData();
result_type result = 0;
for(v_buff_size i = 0; i < s.getSize(); i++) {
v_char8 c = data[i];
result = (31 * result) + c;
}
return result;
}
};
template<>
struct hash<oatpp::data::share::StringKeyLabelCI> {
typedef oatpp::data::share::StringKeyLabelCI argument_type;
typedef v_uint64 result_type;
result_type operator()(oatpp::data::share::StringKeyLabelCI const& s) const noexcept {
auto data = (p_char8) s.getData();
result_type result = 0;
for(v_buff_size i = 0; i < s.getSize(); i++) {
v_char8 c = data[i] | 32;
result = (31 * result) + c;
}
return result;
}
};
}
#endif /* oatpp_data_share_MemoryLabel_hpp */
| vincent-in-black-sesame/oat | src/oatpp/core/data/share/MemoryLabel.hpp | C++ | apache-2.0 | 9,375 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#include "StringTemplate.hpp"
#include "oatpp/core/data/stream/BufferStream.hpp"
namespace oatpp { namespace data { namespace share {
StringTemplate::VectorValueProvider::VectorValueProvider(const std::vector<oatpp::String> *params)
: m_params(params)
{}
oatpp::String StringTemplate::VectorValueProvider::getValue(const Variable& variable, v_uint32 index) {
(void) variable;
return m_params->at(index);
}
StringTemplate::MapValueProvider::MapValueProvider(const std::unordered_map<oatpp::String, oatpp::String> *params)
: m_params(params)
{}
oatpp::String StringTemplate::MapValueProvider::getValue(const Variable& variable, v_uint32 index) {
(void) index;
auto it = m_params->find(variable.name);
if(it != m_params->end()) {
return it->second;
}
return nullptr;
}
StringTemplate::SingleValueProvider::SingleValueProvider(const oatpp::String& value)
: m_value(value)
{}
oatpp::String StringTemplate::SingleValueProvider::getValue(const Variable& variable, v_uint32 index) {
(void) variable;
(void) index;
return m_value;
}
StringTemplate::StringTemplate(const oatpp::String& text, std::vector<Variable>&& variables)
: m_text(text)
, m_variables(variables)
{
v_buff_size prevPos = 0;
for(v_int32 i = 0; i < m_variables.size(); i++) {
const auto& var = m_variables[i];
if(var.posStart < prevPos) {
throw std::runtime_error("[oatpp::data::share::StringTemplate::StringTemplate()]: Error. The template variable positions can't intersect.");
}
if(var.posEnd < var.posStart) {
throw std::runtime_error("[oatpp::data::share::StringTemplate::StringTemplate()]: Error. The template variable can't have a negative size.");
}
if(var.posEnd >= m_text->size()) {
throw std::runtime_error("[oatpp::data::share::StringTemplate::StringTemplate()]: Error. The template variable can't out-bound the template text.");
}
}
}
void StringTemplate::format(stream::ConsistentOutputStream* stream, ValueProvider* valueProvider) const {
v_buff_size prevPos = 0;
for(v_uint32 i = 0; i < m_variables.size(); i++) {
const auto& var = m_variables[i];
const auto& value = valueProvider->getValue(var, i);
if(!value) {
throw std::runtime_error("[oatpp::data::share::StringTemplate::format()]: "
"Error. No value provided for the parameter name=" + *var.name);
}
if(prevPos < var.posStart) {
stream->writeSimple(m_text->data() + prevPos, var.posStart - prevPos);
}
stream->writeSimple(value->data(), value->size());
prevPos = var.posEnd + 1;
}
if(prevPos < m_text->size()) {
stream->writeSimple(m_text->data() + prevPos, m_text->size() - prevPos);
}
}
void StringTemplate::format(stream::ConsistentOutputStream* stream, const std::vector<oatpp::String>& params) const {
VectorValueProvider vp(¶ms);
format(stream, &vp);
}
void StringTemplate::format(stream::ConsistentOutputStream* stream, const std::unordered_map<oatpp::String, oatpp::String>& params) const {
MapValueProvider vp(¶ms);
format(stream, &vp);
}
void StringTemplate::format(stream::ConsistentOutputStream* stream, const oatpp::String& singleValue) const {
SingleValueProvider vp(singleValue);
format(stream, &vp);
}
oatpp::String StringTemplate::format(ValueProvider* valueProvider) const {
stream::BufferOutputStream stream;
format(&stream, valueProvider);
return stream.toString();
}
oatpp::String StringTemplate::format(const std::vector<oatpp::String>& params) const {
stream::BufferOutputStream stream;
format(&stream, params);
return stream.toString();
}
oatpp::String StringTemplate::format(const std::unordered_map<oatpp::String, oatpp::String>& params) const {
stream::BufferOutputStream stream;
format(&stream, params);
return stream.toString();
}
oatpp::String StringTemplate::format(const oatpp::String& singleValue) const {
stream::BufferOutputStream stream;
format(&stream, singleValue);
return stream.toString();
}
const std::vector<StringTemplate::Variable>& StringTemplate::getTemplateVariables() const {
return m_variables;
}
void StringTemplate::setExtraData(const std::shared_ptr<void>& data) {
m_extra = data;
}
std::shared_ptr<void> StringTemplate::getExtraData() const {
return m_extra;
}
}}}
| vincent-in-black-sesame/oat | src/oatpp/core/data/share/StringTemplate.cpp | C++ | apache-2.0 | 5,303 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef oatpp_data_share_StringTemplate_hpp
#define oatpp_data_share_StringTemplate_hpp
#include "oatpp/core/data/stream/Stream.hpp"
#include "oatpp/core/Types.hpp"
#include <unordered_map>
#include <vector>
namespace oatpp { namespace data { namespace share {
/**
* String template.
*/
class StringTemplate {
public:
/**
* Template variable.
*/
struct Variable {
/**
* Position of the first char in the original template string.
*/
v_buff_size posStart;
/**
* Position of the last char in the original template string.
*/
v_buff_size posEnd;
/**
* Name of the template variable.
*/
oatpp::String name;
/**
* Some auxiliary data.
*/
std::shared_ptr<void> extra;
};
public:
/**
* Abstract template value provider.
*/
class ValueProvider {
public:
/**
* Default virtual destructor.
*/
virtual ~ValueProvider() = default;
/**
* Get value for variable.
* @param variable - &l:StringTemplate::Variable;.
* @param index - index of the variable in the template.
* @return - value for the given variable.
*/
virtual oatpp::String getValue(const Variable& variable, v_uint32 index) = 0;
};
/**
* Provider of template variable-values based on the std::vector.
*/
class VectorValueProvider : public ValueProvider {
private:
const std::vector<oatpp::String>* m_params;
public:
VectorValueProvider(const std::vector<oatpp::String>* params);
oatpp::String getValue(const Variable& variable, v_uint32 index) override;
};
/**
* Provider of template variable-values based on the std::unordered_map.
*/
class MapValueProvider : public ValueProvider {
private:
const std::unordered_map<oatpp::String, oatpp::String>* m_params;
public:
MapValueProvider(const std::unordered_map<oatpp::String, oatpp::String>* params);
oatpp::String getValue(const Variable& variable, v_uint32 index) override;
};
/**
* Provider of template variable-values which returns the same value for all variables.
*/
class SingleValueProvider : public ValueProvider {
private:
oatpp::String m_value;
public:
SingleValueProvider(const oatpp::String& value);
oatpp::String getValue(const Variable& variable, v_uint32 index) override;
};
private:
oatpp::String m_text;
std::vector<Variable> m_variables;
std::shared_ptr<void> m_extra;
public:
/**
* Constructor.
* @param text - original template text.
* @param variables - template variables.
*/
StringTemplate(const oatpp::String& text, std::vector<Variable>&& variables);
/**
* Format template.
* @param stream - stream to write result to.
* @param valueProvider - &l:StringTemplate::ValueProvider;.
*/
void format(stream::ConsistentOutputStream* stream, ValueProvider* valueProvider) const;
/**
* Format template using &l:StringTemplate::VectorValueProvider;.
* @param stream - stream to write result to.
* @param params - `std::vector<oatpp::String>`.
*/
void format(stream::ConsistentOutputStream* stream, const std::vector<oatpp::String>& params) const;
/**
* Format template using &l:StringTemplate::MapValueProvider;.
* @param stream - stream to write result to.
* @param params - `std::unordered_map<oatpp::String, oatpp::String>`.
*/
void format(stream::ConsistentOutputStream* stream, const std::unordered_map<oatpp::String, oatpp::String>& params) const;
/**
* Format template using &l:StringTemplate::SingleValueProvider;.
* @param stream - stream to write result to.
* @param singleValue - value.
*/
void format(stream::ConsistentOutputStream* stream, const oatpp::String& singleValue) const;
/**
* Format template.
* @param valueProvider - &l:StringTemplate::ValueProvider;.
* @return - &id:oatpp::String;.
*/
oatpp::String format(ValueProvider* valueProvider) const;
/**
* Format template using &l:StringTemplate::VectorValueProvider;.
* @param params - `std::vector<oatpp::String>`.
* @return - resultant string.
*/
oatpp::String format(const std::vector<oatpp::String>& params) const;
/**
* Format template using &l:StringTemplate::MapValueProvider;.
* @param params - `std::unordered_map<oatpp::String, oatpp::String>`.
* @return - resultant string.
*/
oatpp::String format(const std::unordered_map<oatpp::String, oatpp::String>& params) const;
/**
* Format template using &l:StringTemplate::SingleValueProvider;.
* @param singleValue - value.
* @return - resultant string.
*/
oatpp::String format(const oatpp::String& singleValue) const;
/**
* Get all template variables.
* @return - `std::vector` of &l:StringTemplate::Variable;.
*/
const std::vector<Variable>& getTemplateVariables() const;
/**
* Set some extra data associated with the template.
* @param data
*/
void setExtraData(const std::shared_ptr<void>& data);
/**
* Get extra data associated with the template.
* @return
*/
std::shared_ptr<void> getExtraData() const;
};
}}}
#endif // oatpp_data_share_StringTemplate_hpp
| vincent-in-black-sesame/oat | src/oatpp/core/data/share/StringTemplate.hpp | C++ | apache-2.0 | 6,152 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#include "BufferStream.hpp"
#include "oatpp/core/utils/Binary.hpp"
namespace oatpp { namespace data{ namespace stream {
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// BufferOutputStream
data::stream::DefaultInitializedContext BufferOutputStream::DEFAULT_CONTEXT(data::stream::StreamType::STREAM_INFINITE);
BufferOutputStream::BufferOutputStream(v_buff_size initialCapacity, const std::shared_ptr<void>& captureData)
: m_data(new v_char8[initialCapacity])
, m_capacity(initialCapacity)
, m_position(0)
, m_maxCapacity(-1)
, m_ioMode(IOMode::ASYNCHRONOUS)
, m_capturedData(captureData)
{}
BufferOutputStream::~BufferOutputStream() {
m_capturedData.reset(); // reset capture data before deleting data.
delete [] m_data;
}
v_io_size BufferOutputStream::write(const void *data, v_buff_size count, async::Action& action) {
(void) action;
reserveBytesUpfront(count);
std::memcpy(m_data + m_position, data, count);
m_position += count;
return count;
}
void BufferOutputStream::setOutputStreamIOMode(IOMode ioMode) {
m_ioMode = ioMode;
}
IOMode BufferOutputStream::getOutputStreamIOMode() {
return m_ioMode;
}
Context& BufferOutputStream::getOutputStreamContext() {
return DEFAULT_CONTEXT;
}
void BufferOutputStream::reserveBytesUpfront(v_buff_size count) {
v_buff_size capacityNeeded = m_position + count;
if(capacityNeeded > m_capacity) {
v_buff_size newCapacity = utils::Binary::nextP2(capacityNeeded);
if(newCapacity < 0 || (m_maxCapacity > 0 && newCapacity > m_maxCapacity)) {
newCapacity = m_maxCapacity;
}
if(newCapacity < capacityNeeded) {
throw std::runtime_error("[oatpp::data::stream::BufferOutputStream::reserveBytesUpfront()]: Error. Unable to allocate requested memory.");
}
p_char8 newData = new v_char8[newCapacity];
std::memcpy(newData, m_data, m_position);
delete [] m_data;
m_data = newData;
m_capacity = newCapacity;
}
}
p_char8 BufferOutputStream::getData() {
return m_data;
}
v_buff_size BufferOutputStream::getCapacity() {
return m_capacity;
}
v_buff_size BufferOutputStream::getCurrentPosition() {
return m_position;
}
void BufferOutputStream::setCurrentPosition(v_buff_size position) {
m_position = position;
}
void BufferOutputStream::reset(v_buff_size initialCapacity) {
delete [] m_data;
m_data = new v_char8[initialCapacity];
m_capacity = initialCapacity;
m_position = 0;
}
oatpp::String BufferOutputStream::toString() {
return oatpp::String((const char*) m_data, m_position);
}
oatpp::String BufferOutputStream::getSubstring(v_buff_size pos, v_buff_size count) {
if(pos + count <= m_position) {
return oatpp::String((const char *) (m_data + pos), count);
} else {
return oatpp::String((const char *) (m_data + pos), m_position - pos);
}
}
oatpp::v_io_size BufferOutputStream::flushToStream(OutputStream* stream) {
return stream->writeExactSizeDataSimple(m_data, m_position);
}
oatpp::async::CoroutineStarter BufferOutputStream::flushToStreamAsync(const std::shared_ptr<BufferOutputStream>& _this, const std::shared_ptr<OutputStream>& stream) {
class WriteDataCoroutine : public oatpp::async::Coroutine<WriteDataCoroutine> {
private:
std::shared_ptr<BufferOutputStream> m_this;
std::shared_ptr<oatpp::data::stream::OutputStream> m_stream;
data::buffer::InlineWriteData m_inlineData;
public:
WriteDataCoroutine(const std::shared_ptr<BufferOutputStream>& _this,
const std::shared_ptr<oatpp::data::stream::OutputStream>& stream)
: m_this(_this)
, m_stream(stream)
{}
Action act() override {
if(m_inlineData.currBufferPtr == nullptr) {
m_inlineData.currBufferPtr = m_this->m_data;
m_inlineData.bytesLeft = m_this->m_position;
}
return m_stream.get()->writeExactSizeDataAsyncInline(m_inlineData, finish());
}
};
return WriteDataCoroutine::start(_this, stream);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// BufferInputStream
data::stream::DefaultInitializedContext BufferInputStream::DEFAULT_CONTEXT(data::stream::StreamType::STREAM_FINITE);
BufferInputStream::BufferInputStream(const std::shared_ptr<std::string>& memoryHandle,
const void* data,
v_buff_size size,
const std::shared_ptr<void>& captureData)
: m_memoryHandle(memoryHandle)
, m_data((p_char8) data)
, m_size(size)
, m_position(0)
, m_ioMode(IOMode::ASYNCHRONOUS)
, m_capturedData(captureData)
{}
BufferInputStream::BufferInputStream(const oatpp::String& data, const std::shared_ptr<void>& captureData)
: BufferInputStream(data.getPtr(), (p_char8) data->data(), data->size(), captureData)
{}
void BufferInputStream::reset(const std::shared_ptr<std::string>& memoryHandle,
p_char8 data,
v_buff_size size,
const std::shared_ptr<void>& captureData)
{
m_memoryHandle = memoryHandle;
m_data = data;
m_size = size;
m_position = 0;
m_capturedData = captureData;
}
void BufferInputStream::reset() {
m_memoryHandle = nullptr;
m_data = nullptr;
m_size = 0;
m_position = 0;
m_capturedData.reset();
}
v_io_size BufferInputStream::read(void *data, v_buff_size count, async::Action& action) {
(void) action;
v_buff_size desiredAmount = count;
if(desiredAmount > m_size - m_position) {
desiredAmount = m_size - m_position;
}
std::memcpy(data, &m_data[m_position], desiredAmount);
m_position += desiredAmount;
return desiredAmount;
}
void BufferInputStream::setInputStreamIOMode(IOMode ioMode) {
m_ioMode = ioMode;
}
IOMode BufferInputStream::getInputStreamIOMode() {
return m_ioMode;
}
Context& BufferInputStream::getInputStreamContext() {
return DEFAULT_CONTEXT;
}
std::shared_ptr<std::string> BufferInputStream::getDataMemoryHandle() {
return m_memoryHandle;
}
p_char8 BufferInputStream::getData() {
return m_data;
}
v_buff_size BufferInputStream::getDataSize() {
return m_size;
}
v_buff_size BufferInputStream::getCurrentPosition() {
return m_position;
}
void BufferInputStream::setCurrentPosition(v_buff_size position) {
m_position = position;
}
v_io_size BufferInputStream::peek(void *data, v_buff_size count, async::Action &action) {
(void) action;
v_buff_size desiredAmount = count;
if(desiredAmount > m_size - m_position) {
desiredAmount = m_size - m_position;
}
std::memcpy(data, &m_data[m_position], desiredAmount);
return desiredAmount;
}
v_io_size BufferInputStream::availableToRead() const {
return m_size - m_position;
}
v_io_size BufferInputStream::commitReadOffset(v_buff_size count) {
if(count > m_size - m_position) {
count = m_size - m_position;
}
m_position += count;
return count;
}
}}}
| vincent-in-black-sesame/oat | src/oatpp/core/data/stream/BufferStream.cpp | C++ | apache-2.0 | 8,020 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef oatpp_data_stream_BufferStream_hpp
#define oatpp_data_stream_BufferStream_hpp
#include "Stream.hpp"
namespace oatpp { namespace data{ namespace stream {
/**
* BufferOutputStream
*/
class BufferOutputStream : public ConsistentOutputStream {
public:
static data::stream::DefaultInitializedContext DEFAULT_CONTEXT;
private:
p_char8 m_data;
v_buff_size m_capacity;
v_buff_size m_position;
v_buff_size m_maxCapacity;
IOMode m_ioMode;
private:
std::shared_ptr<void> m_capturedData;
public:
/**
* Constructor.
* @param growBytes
* @param captureData - capture auxiliary data to not get deleted until it's done with the stream.
*/
BufferOutputStream(v_buff_size initialCapacity = 2048, const std::shared_ptr<void>& captureData = nullptr);
/**
* Virtual destructor.
*/
~BufferOutputStream();
/**
* Write `count` of bytes to stream.
* @param data - data to write.
* @param count - number of bytes to write.
* @param action - async specific action. If action is NOT &id:oatpp::async::Action::TYPE_NONE;, then
* caller MUST return this action on coroutine iteration.
* @return - actual number of bytes written. &id:oatpp::v_io_size;.
*/
v_io_size write(const void *data, v_buff_size count, async::Action& action) override;
/**
* Set stream I/O mode.
* @throws
*/
void setOutputStreamIOMode(IOMode ioMode) override;
/**
* Get stream I/O mode.
* @return
*/
IOMode getOutputStreamIOMode() override;
/**
* Get stream context.
* @return
*/
Context& getOutputStreamContext() override;
/**
* Reserve bytes for future writes.
*/
void reserveBytesUpfront(v_buff_size count);
/**
* Get pointer to data.
* @return - pointer to data.
*/
p_char8 getData();
/**
* Get current capacity.
* Capacity may change.
* @return
*/
v_buff_size getCapacity();
/**
* Get current data write position.
* @return - current data write position.
*/
v_buff_size getCurrentPosition();
/**
* Set current data write position.
* @param position - data write position.
*/
void setCurrentPosition(v_buff_size position);
/**
* Reset stream buffer and its capacity. Also reset write position.
* @param initialCapacity
*/
void reset(v_buff_size initialCapacity = 2048);
/**
* Copy data to &id:oatpp::String;.
* @return
*/
oatpp::String toString();
/**
* Create &id:oatpp::String; from part of buffer.
* @param pos - starting position in buffer.
* @param count - size of bytes to write to substring.
* @return - &id:oatpp::String;
*/
oatpp::String getSubstring(v_buff_size pos, v_buff_size count);
/**
* Write all bytes from buffer to stream.
* @param stream - stream to flush all data to.
* @return - actual amount of bytes flushed.
*/
oatpp::v_io_size flushToStream(OutputStream* stream);
/**
* Write all bytes from buffer to stream in async manner.
* @param _this - pointer to `this` buffer.
* @param stream - stream to flush all data to.
* @return - &id:oatpp::async::CoroutineStarter;.
*/
static oatpp::async::CoroutineStarter flushToStreamAsync(const std::shared_ptr<BufferOutputStream>& _this, const std::shared_ptr<OutputStream>& stream);
};
/**
* BufferInputStream
*/
class BufferInputStream : public BufferedInputStream {
public:
static data::stream::DefaultInitializedContext DEFAULT_CONTEXT;
private:
std::shared_ptr<std::string> m_memoryHandle;
p_char8 m_data;
v_buff_size m_size;
v_buff_size m_position;
IOMode m_ioMode;
private:
std::shared_ptr<void> m_capturedData;
public:
/**
* Constructor.
* @param memoryHandle - buffer memory handle. May be nullptr.
* @param data - pointer to buffer data.
* @param size - size of the buffer.
* @param captureData - capture auxiliary data to not get deleted until it's done with the stream.
*/
BufferInputStream(const std::shared_ptr<std::string>& memoryHandle,
const void* data,
v_buff_size size,
const std::shared_ptr<void>& captureData = nullptr);
/**
* Constructor.
* @param data - buffer.
* @param captureData - capture auxiliary data to not get deleted until it's done with the stream.
*/
BufferInputStream(const oatpp::String& data, const std::shared_ptr<void>& captureData = nullptr);
/**
* Reset stream data and set position to `0`.
* @param memoryHandle - buffer memory handle. May be nullptr.
* @param data - pointer to buffer data.
* @param size - size of the buffer.
* @param captureData - capture auxiliary data to not get deleted until it's done with the stream.
*/
void reset(const std::shared_ptr<std::string>& memoryHandle,
p_char8 data,
v_buff_size size,
const std::shared_ptr<void>& captureData = nullptr);
/**
* Same as `reset(nullptr, nullptr, 0);.`
*/
void reset();
/**
* Read data from stream. <br>
* It is a legal case if return result < count. Caller should handle this!
* *Calls to this method are always NON-BLOCKING*
* @param data - buffer to read data to.
* @param count - size of the buffer.
* @param action - async specific action. If action is NOT &id:oatpp::async::Action::TYPE_NONE;, then
* caller MUST return this action on coroutine iteration.
* @return - actual number of bytes read. 0 - designates end of the buffer.
*/
v_io_size read(void *data, v_buff_size count, async::Action& action) override;
/**
* Set stream I/O mode.
* @throws
*/
void setInputStreamIOMode(IOMode ioMode) override;
/**
* Get stream I/O mode.
* @return
*/
IOMode getInputStreamIOMode() override;
/**
* Get stream context.
* @return
*/
Context& getInputStreamContext() override;
/**
* Get data memory handle.
* @return - data memory handle.
*/
std::shared_ptr<std::string> getDataMemoryHandle();
/**
* Get pointer to data.
* @return - pointer to data.
*/
p_char8 getData();
/**
* Get data size.
* @return - data size.
*/
v_buff_size getDataSize();
/**
* Get current data read position.
* @return - current data read position.
*/
v_buff_size getCurrentPosition();
/**
* Set current data read position.
* @param position - data read position.
*/
void setCurrentPosition(v_buff_size position);
/**
* Peek up to count of bytes int he buffer
* @param data
* @param count
* @return [1..count], IOErrors.
*/
v_io_size peek(void *data, v_buff_size count, async::Action& action) override;
/**
* Amount of bytes currently available to read from buffer.
* @return &id:oatpp::v_io_size;.
*/
v_io_size availableToRead() const override;
/**
* Commit read offset
* @param count
* @return [1..count], IOErrors.
*/
v_io_size commitReadOffset(v_buff_size count) override;
};
}}}
#endif // oatpp_data_stream_BufferStream_hpp
| vincent-in-black-sesame/oat | src/oatpp/core/data/stream/BufferStream.hpp | C++ | apache-2.0 | 7,982 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Benedikt-Alexander Mokroß <github@bamkrs.de>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#include "FIFOStream.hpp"
#include "oatpp/core/utils/Binary.hpp"
namespace oatpp { namespace data { namespace stream {
data::stream::DefaultInitializedContext FIFOInputStream::DEFAULT_CONTEXT(data::stream::StreamType::STREAM_FINITE);
FIFOInputStream::FIFOInputStream(v_buff_size initialSize)
: m_memoryHandle(std::make_shared<std::string>(initialSize, (char)0))
, m_fifo(std::make_shared<data::buffer::FIFOBuffer>((void*)m_memoryHandle->data(), m_memoryHandle->size(), 0, 0, false))
, m_maxCapacity(-1) {
}
void FIFOInputStream::reset() {
m_fifo->setBufferPosition(0, 0, false);
}
v_io_size FIFOInputStream::read(void *data, v_buff_size count, async::Action& action) {
(void) action;
return m_fifo->read(data, count);
}
void FIFOInputStream::setInputStreamIOMode(IOMode ioMode) {
m_ioMode = ioMode;
}
IOMode FIFOInputStream::getInputStreamIOMode() {
return m_ioMode;
}
Context& FIFOInputStream::getInputStreamContext() {
return DEFAULT_CONTEXT;
}
std::shared_ptr<std::string> FIFOInputStream::getDataMemoryHandle() {
return m_memoryHandle;
}
v_io_size FIFOInputStream::write(const void *data, v_buff_size count, async::Action &action) {
(void) action;
reserveBytesUpfront(count);
return m_fifo->write(data, count);
}
void FIFOInputStream::reserveBytesUpfront(v_buff_size count) {
v_buff_size capacityNeeded = availableToRead() + count;
if(capacityNeeded > m_fifo->getBufferSize()) {
v_buff_size newCapacity = utils::Binary::nextP2(capacityNeeded);
if(newCapacity < 0 || (m_maxCapacity > 0 && newCapacity > m_maxCapacity)) {
newCapacity = m_maxCapacity;
}
if(newCapacity < capacityNeeded) {
throw std::runtime_error("[oatpp::data::stream::BufferOutputStream::reserveBytesUpfront()]: Error. Unable to allocate requested memory.");
}
// ToDo: In-Memory-Resize
auto newHandle = std::make_shared<std::string>(newCapacity, (char)0);
v_io_size oldSize = m_fifo->availableToRead();
m_fifo->read((void*)newHandle->data(), oldSize);
auto newFifo = std::make_shared<data::buffer::FIFOBuffer>((void*)newHandle->data(), newHandle->size(), 0, oldSize, oldSize > 0);
m_memoryHandle = newHandle;
m_fifo = newFifo;
}
}
v_io_size FIFOInputStream::readAndWriteToStream(data::stream::OutputStream *stream,
v_buff_size count,
async::Action &action) {
return m_fifo->readAndWriteToStream(stream, count, action);
}
v_io_size FIFOInputStream::readFromStreamAndWrite(data::stream::InputStream *stream,
v_buff_size count,
async::Action &action) {
reserveBytesUpfront(count);
return m_fifo->readFromStreamAndWrite(stream, count, action);
}
v_io_size FIFOInputStream::flushToStream(data::stream::OutputStream *stream) {
return m_fifo->flushToStream(stream);
}
async::CoroutineStarter FIFOInputStream::flushToStreamAsync(const std::shared_ptr<data::stream::OutputStream> &stream) {
return m_fifo->flushToStreamAsync(stream);
}
v_io_size FIFOInputStream::availableToWrite() {
return m_fifo->availableToWrite();
}
v_io_size FIFOInputStream::peek(void *data, v_buff_size count, async::Action &action) {
(void) action;
return m_fifo->peek(data, count);
}
v_io_size FIFOInputStream::availableToRead() const {
return m_fifo->availableToRead();
}
v_io_size FIFOInputStream::commitReadOffset(v_buff_size count) {
return m_fifo->commitReadOffset(count);
}
}}} | vincent-in-black-sesame/oat | src/oatpp/core/data/stream/FIFOStream.cpp | C++ | apache-2.0 | 4,559 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Benedikt-Alexander Mokroß <github@bamkrs.de>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef oatpp_data_stream_FIFOStream_hpp
#define oatpp_data_stream_FIFOStream_hpp
#include "Stream.hpp"
#include "oatpp/core/data/buffer/FIFOBuffer.hpp"
namespace oatpp { namespace data { namespace stream {
/**
* FIFOInputStream
*/
class FIFOInputStream : public BufferedInputStream, public WriteCallback {
public:
static data::stream::DefaultInitializedContext DEFAULT_CONTEXT;
private:
std::shared_ptr<std::string> m_memoryHandle;
std::shared_ptr<data::buffer::FIFOBuffer> m_fifo;
v_buff_size m_maxCapacity;
IOMode m_ioMode;
public:
/**
* Constructor.
* @param data - buffer.
*/
FIFOInputStream(v_buff_size initialSize = 4096);
static std::shared_ptr<FIFOInputStream> createShared(v_buff_size initialSize = 4096) {
return std::make_shared<FIFOInputStream>(initialSize);
}
/**
* Discards all data in the buffer and resets it to an empty state
*/
void reset();
/**
* Read data from stream. <br>
* It is a legal case if return result < count. Caller should handle this!
* *Calls to this method are always NON-BLOCKING*
* @param data - buffer to read data to.
* @param count - size of the buffer.
* @param action - async specific action. If action is NOT &id:oatpp::async::Action::TYPE_NONE;, then
* caller MUST return this action on coroutine iteration.
* @return - actual number of bytes read. 0 - designates end of the buffer.
*/
v_io_size read(void *data, v_buff_size count, async::Action& action) override;
/**
* Set stream I/O mode.
* @throws
*/
void setInputStreamIOMode(IOMode ioMode) override;
/**
* Get stream I/O mode.
* @return
*/
IOMode getInputStreamIOMode() override;
/**
* Get stream context.
* @return
*/
Context& getInputStreamContext() override;
/**
* Get data memory handle.
* @return - data memory handle.
*/
std::shared_ptr<std::string> getDataMemoryHandle();
/**
* Write operation callback.
* @param data - pointer to data.
* @param count - size of the data in bytes.
* @param action - async specific action. If action is NOT &id:oatpp::async::Action::TYPE_NONE;, then
* caller MUST return this action on coroutine iteration.
* @return - actual number of bytes written. 0 - to indicate end-of-file.
*/
v_io_size write(const void *data, v_buff_size count, async::Action &action) override;
/**
* Peek up to count of bytes int he buffer
* @param data
* @param count
* @return [1..count], IOErrors.
*/
v_io_size peek(void *data, v_buff_size count, async::Action& action) override;
/**
* Amount of bytes currently available to read from buffer.
* @return &id:oatpp::v_io_size;.
*/
v_io_size availableToRead() const override;
/**
* Commit read offset
* @param count
* @return [1..count], IOErrors.
*/
v_io_size commitReadOffset(v_buff_size count) override;
/**
* Reserve bytes for future writes. Check &id:oatpp::data::stream::FIFOStream::availableToWrite for the capacity.
*/
void reserveBytesUpfront(v_buff_size count);
/**
* call read and then write bytes read to output stream
* @param stream
* @param count
* @param action
* @return [1..count], IOErrors.
*/
v_io_size readAndWriteToStream(data::stream::OutputStream* stream, v_buff_size count, async::Action& action);
/**
* call stream.read() and then write bytes read to buffer
* @param stream
* @param count
* @param action
* @return
*/
v_io_size readFromStreamAndWrite(data::stream::InputStream* stream, v_buff_size count, async::Action& action);
/**
* flush all availableToRead bytes to stream
* @param stream
* @return
*/
v_io_size flushToStream(data::stream::OutputStream* stream);
/**
* flush all availableToRead bytes to stream in asynchronous manner
* @param stream - &id:data::stream::OutputStream;.
* @return - &id:async::CoroutineStarter;.
*/
async::CoroutineStarter flushToStreamAsync(const std::shared_ptr<data::stream::OutputStream>& stream);
/**
* Amount of buffer space currently available for data writes.
* @return &id:oatpp::v_io_size;.
*/
v_io_size availableToWrite();
};
}}}
#endif // oatpp_data_stream_FIFOStream_hpp
| vincent-in-black-sesame/oat | src/oatpp/core/data/stream/FIFOStream.hpp | C++ | apache-2.0 | 5,236 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#include "FileStream.hpp"
namespace oatpp { namespace data{ namespace stream {
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// FileInputStream
oatpp::data::stream::DefaultInitializedContext FileInputStream::DEFAULT_CONTEXT(data::stream::StreamType::STREAM_FINITE);
FileInputStream::FileInputStream(FileInputStream&& other)
: m_file(other.m_file)
, m_ownsFile(other.m_ownsFile)
, m_ioMode(other.m_ioMode)
{
other.m_file = nullptr;
other.m_ownsFile = false;
}
FileInputStream::FileInputStream(std::FILE* file, bool ownsFile, const std::shared_ptr<void>& captureData)
: m_file(file)
, m_ownsFile(ownsFile)
, m_ioMode(IOMode::ASYNCHRONOUS)
, m_capturedData(captureData)
{}
FileInputStream::FileInputStream(const char* filename, const std::shared_ptr<void>& captureData)
: FileInputStream(std::fopen(filename, "rb"), true, captureData)
{
if(!m_file) {
OATPP_LOGE("[oatpp::data::stream::FileInputStream::FileInputStream(filename)]", "Error. Can't open file '%s'.", filename);
throw std::runtime_error("[oatpp::data::stream::FileInputStream::FileInputStream(filename)]: Error. Can't open file.");
}
}
FileInputStream::~FileInputStream() {
this->close();
}
std::FILE* FileInputStream::getFile() {
return m_file;
}
v_io_size FileInputStream::read(void *data, v_buff_size count, async::Action& action) {
(void) action;
if(m_file != nullptr) {
return std::fread(data, 1, count, m_file);
}
return oatpp::IOError::BROKEN_PIPE;
}
void FileInputStream::setInputStreamIOMode(IOMode ioMode) {
m_ioMode = ioMode;
}
IOMode FileInputStream::getInputStreamIOMode() {
return m_ioMode;
}
Context& FileInputStream::getInputStreamContext() {
return DEFAULT_CONTEXT;
}
void FileInputStream::close() {
if(m_ownsFile && m_file) {
std::fclose(m_file);
}
}
FileInputStream& FileInputStream::operator=(FileInputStream&& other) {
if(this != &other) {
close();
}
m_file = other.m_file;
m_ownsFile = other.m_ownsFile;
m_ioMode = other.m_ioMode;
other.m_file = nullptr;
other.m_ownsFile = false;
return *this;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// FileOutputStream
oatpp::data::stream::DefaultInitializedContext FileOutputStream::DEFAULT_CONTEXT(data::stream::StreamType::STREAM_FINITE);
FileOutputStream::FileOutputStream(FileOutputStream&& other)
: m_file(other.m_file)
, m_ownsFile(other.m_ownsFile)
, m_ioMode(other.m_ioMode)
{
other.m_file = nullptr;
other.m_ownsFile = false;
}
FileOutputStream::FileOutputStream(std::FILE* file, bool ownsFile, const std::shared_ptr<void>& captureData)
: m_file(file)
, m_ownsFile(ownsFile)
, m_ioMode(IOMode::ASYNCHRONOUS)
, m_capturedData(captureData)
{}
FileOutputStream::FileOutputStream(const char* filename, const char* mode, const std::shared_ptr<void>& captureData)
: FileOutputStream(std::fopen(filename, mode), true, captureData)
{
if(!m_file) {
OATPP_LOGE("[oatpp::data::stream::FileOutputStream::FileOutputStream(filename, mode)]", "Error. Can't open file '%s'.", filename);
throw std::runtime_error("[oatpp::data::stream::FileOutputStream::FileOutputStream(filename, mode)]: Error. Can't open file.");
}
}
FileOutputStream::~FileOutputStream() {
this->close();
}
std::FILE* FileOutputStream::getFile() {
return m_file;
}
v_io_size FileOutputStream::write(const void *data, v_buff_size count, async::Action& action) {
(void) action;
return std::fwrite(data, 1, count, m_file);
}
void FileOutputStream::setOutputStreamIOMode(IOMode ioMode) {
m_ioMode = ioMode;
}
IOMode FileOutputStream::getOutputStreamIOMode() {
return m_ioMode;
}
Context& FileOutputStream::getOutputStreamContext() {
return DEFAULT_CONTEXT;
}
void FileOutputStream::close() {
if(m_ownsFile && m_file) {
std::fclose(m_file);
}
}
FileOutputStream& FileOutputStream::operator=(FileOutputStream&& other) {
if(this != &other) {
close();
}
m_file = other.m_file;
m_ownsFile = other.m_ownsFile;
m_ioMode = other.m_ioMode;
other.m_file = nullptr;
other.m_ownsFile = false;
return *this;
}
}}}
| vincent-in-black-sesame/oat | src/oatpp/core/data/stream/FileStream.cpp | C++ | apache-2.0 | 5,224 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef oatpp_data_stream_FileStream_hpp
#define oatpp_data_stream_FileStream_hpp
#include "Stream.hpp"
#include <cstdio>
namespace oatpp { namespace data{ namespace stream {
/**
* Wrapper over `std::FILE`.
*/
class FileInputStream : public InputStream {
public:
static oatpp::data::stream::DefaultInitializedContext DEFAULT_CONTEXT;
private:
std::FILE* m_file;
bool m_ownsFile;
IOMode m_ioMode;
private:
std::shared_ptr<void> m_capturedData;
public:
FileInputStream(const FileInputStream&) = delete;
FileInputStream &operator=(const FileInputStream&) = delete;
/**
* Move constructor.
* @param other
*/
FileInputStream(FileInputStream&& other);
/**
* Constructor.
* @param file - file.
* @param ownsFile - if `true` then call close on `FileInputStream` destruction.
* @param captureData - capture auxiliary data to not get deleted until it's done with the stream.
*/
FileInputStream(std::FILE* file, bool ownsFile, const std::shared_ptr<void>& captureData = nullptr);
/**
* Constructor.
* @param filename - name of the file.
* @param captureData - capture auxiliary data to not get deleted until it's done with the stream.
*/
FileInputStream(const char* filename, const std::shared_ptr<void>& captureData = nullptr);
/**
* Virtual destructor.
*/
~FileInputStream();
/**
* Get file.
* @return
*/
std::FILE* getFile();
/**
* Read data from stream up to count bytes, and return number of bytes actually read. <br>
* It is a legal case if return result < count. Caller should handle this!
* @param data - buffer to read data to.
* @param count - size of the buffer.
* @param action - async specific action. If action is NOT &id:oatpp::async::Action::TYPE_NONE;, then
* caller MUST return this action on coroutine iteration.
* @return - actual number of bytes read.
*/
v_io_size read(void *data, v_buff_size count, async::Action& action) override;
/**
* Set stream I/O mode.
* @throws
*/
void setInputStreamIOMode(IOMode ioMode) override;
/**
* Get stream I/O mode.
* @return
*/
IOMode getInputStreamIOMode() override;
/**
* Get stream context.
* @return
*/
Context& getInputStreamContext() override;
/**
* Close file.
*/
void close();
FileInputStream& operator=(FileInputStream&& other);
};
/**
* Wrapper over `std::FILE`.
*/
class FileOutputStream : public OutputStream {
public:
static oatpp::data::stream::DefaultInitializedContext DEFAULT_CONTEXT;
private:
std::FILE* m_file;
bool m_ownsFile;
IOMode m_ioMode;
private:
std::shared_ptr<void> m_capturedData;
public:
FileOutputStream(const FileOutputStream&) = delete;
FileOutputStream &operator=(const FileOutputStream&) = delete;
/**
* Move constructor.
* @param other
*/
FileOutputStream(FileOutputStream&& other);
/**
* Constructor.
* @param file - file.
* @param ownsFile - if `true` then call close on `FileInputStream` destruction.
* @param captureData - capture auxiliary data to not get deleted until it's done with the stream.
*/
FileOutputStream(std::FILE* file, bool ownsFile, const std::shared_ptr<void>& captureData = nullptr);
/**
* Constructor.
* @param filename - name of the file.
* @param mode - ("wb" - create new/override, "ab" - create new/append).
* @param captureData - capture auxiliary data to not get deleted until it's done with the stream.
*/
FileOutputStream(const char* filename, const char* mode = "wb", const std::shared_ptr<void>& captureData = nullptr);
/**
* Virtual destructor.
*/
~FileOutputStream();
/**
* Get file.
* @return
*/
std::FILE* getFile();
/**
* Write data to stream up to count bytes, and return number of bytes actually written. <br>
* It is a legal case if return result < count. Caller should handle this!
* @param data - data to write.
* @param count - number of bytes to write.
* @param action - async specific action. If action is NOT &id:oatpp::async::Action::TYPE_NONE;, then
* caller MUST return this action on coroutine iteration.
* @return - actual number of bytes written. &id:oatpp::v_io_size;.
*/
v_io_size write(const void *data, v_buff_size count, async::Action& action) override;
/**
* Set stream I/O mode.
* @throws
*/
void setOutputStreamIOMode(IOMode ioMode) override;
/**
* Get stream I/O mode.
* @return
*/
IOMode getOutputStreamIOMode() override;
/**
* Get stream context.
* @return
*/
Context& getOutputStreamContext() override;
/**
* Close file.
*/
void close();
FileOutputStream& operator=(FileOutputStream&& other);
};
}}}
#endif // oatpp_data_stream_FileStream_hpp
| vincent-in-black-sesame/oat | src/oatpp/core/data/stream/FileStream.hpp | C++ | apache-2.0 | 5,757 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#include "./Stream.hpp"
#include "oatpp/core/utils/ConversionUtils.hpp"
namespace oatpp { namespace data{ namespace stream {
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// WriteCallback
v_io_size WriteCallback::write(data::buffer::InlineWriteData& inlineData, async::Action& action) {
auto res = write(inlineData.currBufferPtr, inlineData.bytesLeft, action);
if(res > 0) {
inlineData.inc(res);
}
return res;
}
v_io_size WriteCallback::writeSimple(const void *data, v_buff_size count) {
async::Action action;
auto res = write(data, count, action);
if(!action.isNone()) {
OATPP_LOGE("[oatpp::data::stream::WriteCallback::writeSimple()]", "Error. writeSimple is called on a stream in Async mode.");
throw std::runtime_error("[oatpp::data::stream::WriteCallback::writeSimple()]: Error. writeSimple is called on a stream in Async mode.");
}
return res;
}
v_io_size WriteCallback::writeExactSizeDataSimple(data::buffer::InlineWriteData& inlineData) {
auto initialCount = inlineData.bytesLeft;
while(inlineData.bytesLeft > 0) {
async::Action action;
auto res = write(inlineData, action);
if(!action.isNone()) {
OATPP_LOGE("[oatpp::data::stream::WriteCallback::writeExactSizeDataSimple()]", "Error. writeExactSizeDataSimple() is called on a stream in Async mode.");
throw std::runtime_error("[oatpp::data::stream::WriteCallback::writeExactSizeDataSimple()]: Error. writeExactSizeDataSimple() is called on a stream in Async mode.");
}
if(res == IOError::BROKEN_PIPE || res == IOError::ZERO_VALUE) {
break;
}
}
return initialCount - inlineData.bytesLeft;
}
v_io_size WriteCallback::writeExactSizeDataSimple(const void *data, v_buff_size count) {
data::buffer::InlineWriteData inlineData(data, count);
return writeExactSizeDataSimple(inlineData);
}
async::Action WriteCallback::writeExactSizeDataAsyncInline(data::buffer::InlineWriteData& inlineData, async::Action&& nextAction) {
if(inlineData.bytesLeft > 0) {
async::Action action;
auto res = write(inlineData, action);
if (!action.isNone()) {
return action;
}
if (res > 0) {
return async::Action::createActionByType(async::Action::TYPE_REPEAT);
} else {
switch (res) {
case IOError::BROKEN_PIPE:
return new AsyncIOError(IOError::BROKEN_PIPE);
case IOError::ZERO_VALUE:
break;
case IOError::RETRY_READ:
return async::Action::createActionByType(async::Action::TYPE_REPEAT);
case IOError::RETRY_WRITE:
return async::Action::createActionByType(async::Action::TYPE_REPEAT);
default:
OATPP_LOGE("[oatpp::data::stream::writeExactSizeDataAsyncInline()]", "Error. Unknown IO result.");
return new async::Error(
"[oatpp::data::stream::writeExactSizeDataAsyncInline()]: Error. Unknown IO result.");
}
}
}
return std::forward<async::Action>(nextAction);
}
async::CoroutineStarter WriteCallback::writeExactSizeDataAsync(const void* data, v_buff_size size) {
class WriteDataCoroutine : public oatpp::async::Coroutine<WriteDataCoroutine> {
private:
WriteCallback* m_this;
data::buffer::InlineWriteData m_inlineData;
public:
WriteDataCoroutine(WriteCallback* _this,
const void* data, v_buff_size size)
: m_this(_this)
, m_inlineData(data, size)
{}
Action act() override {
return m_this->writeExactSizeDataAsyncInline(m_inlineData, finish());
}
};
return WriteDataCoroutine::start(this, data, size);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ReadCallback
v_io_size ReadCallback::read(data::buffer::InlineReadData& inlineData, async::Action& action) {
auto res = read(inlineData.currBufferPtr, inlineData.bytesLeft, action);
if(res > 0) {
inlineData.inc(res);
}
return res;
}
v_io_size ReadCallback::readExactSizeDataSimple(data::buffer::InlineReadData& inlineData) {
auto initialCount = inlineData.bytesLeft;
while(inlineData.bytesLeft > 0) {
async::Action action;
auto res = read(inlineData, action);
if(!action.isNone()) {
OATPP_LOGE("[oatpp::data::stream::ReadCallback::readExactSizeDataSimple()]", "Error. readExactSizeDataSimple() is called on a stream in Async mode.");
throw std::runtime_error("[oatpp::data::stream::ReadCallback::readExactSizeDataSimple()]: Error. readExactSizeDataSimple() is called on a stream in Async mode.");
}
if(res <= 0 && res != IOError::RETRY_READ && res != IOError::RETRY_WRITE) {
break;
}
}
return initialCount - inlineData.bytesLeft;
}
v_io_size ReadCallback::readExactSizeDataSimple(void *data, v_buff_size count) {
data::buffer::InlineReadData inlineData(data, count);
return readExactSizeDataSimple(inlineData);
}
async::Action ReadCallback::readExactSizeDataAsyncInline(data::buffer::InlineReadData& inlineData, async::Action&& nextAction) {
if(inlineData.bytesLeft > 0) {
async::Action action;
auto res = read(inlineData, action);
if (!action.isNone()) {
return action;
}
if (res > 0) {
return async::Action::createActionByType(async::Action::TYPE_REPEAT);
} else {
switch (res) {
case IOError::BROKEN_PIPE:
return new AsyncIOError("[oatpp::data::stream::readExactSizeDataAsyncInline()]: IOError::BROKEN_PIPE", IOError::BROKEN_PIPE);
case IOError::ZERO_VALUE:
break;
case IOError::RETRY_READ:
return async::Action::createActionByType(async::Action::TYPE_REPEAT);
case IOError::RETRY_WRITE:
return async::Action::createActionByType(async::Action::TYPE_REPEAT);
default:
OATPP_LOGE("[oatpp::data::stream::readExactSizeDataAsyncInline()]", "Error. Unknown IO result.");
return new async::Error(
"[oatpp::data::stream::readExactSizeDataAsyncInline()]: Error. Unknown IO result.");
}
}
}
return std::forward<async::Action>(nextAction);
}
async::Action ReadCallback::readSomeDataAsyncInline(data::buffer::InlineReadData& inlineData, async::Action&& nextAction) {
if(inlineData.bytesLeft > 0) {
async::Action action;
auto res = read(inlineData, action);
if(!action.isNone()) {
return action;
}
if(res < 0) {
switch (res) {
case IOError::BROKEN_PIPE:
return new AsyncIOError(IOError::BROKEN_PIPE);
// case IOError::ZERO_VALUE:
// break;
case IOError::RETRY_READ:
return async::Action::createActionByType(async::Action::TYPE_REPEAT);
case IOError::RETRY_WRITE:
return async::Action::createActionByType(async::Action::TYPE_REPEAT);
default:
OATPP_LOGE("[oatpp::data::stream::readSomeDataAsyncInline()]", "Error. Unknown IO result.");
return new async::Error(
"[oatpp::data::stream::readSomeDataAsyncInline()]: Error. Unknown IO result.");
}
}
}
return std::forward<async::Action>(nextAction);
}
v_io_size ReadCallback::readSimple(void *data, v_buff_size count) {
async::Action action;
auto res = read(data, count, action);
if(!action.isNone()) {
OATPP_LOGE("[oatpp::data::stream::ReadCallback::readSimple()]", "Error. readSimple is called on a stream in Async mode.");
throw std::runtime_error("[oatpp::data::stream::ReadCallback::readSimple()]: Error. readSimple is called on a stream in Async mode.");
}
return res;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Context
Context::Context(Properties&& properties)
: m_properties(std::forward<Properties>(properties))
{}
const Context::Properties& Context::getProperties() const {
return m_properties;
}
Context::Properties& Context::getMutableProperties() {
return m_properties;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// DefaultInitializedContext
DefaultInitializedContext::DefaultInitializedContext(StreamType streamType)
: m_streamType(streamType)
{}
DefaultInitializedContext::DefaultInitializedContext(StreamType streamType, Properties&& properties)
: Context(std::forward<Properties>(properties))
, m_streamType(streamType)
{}
void DefaultInitializedContext::init() {
// DO NOTHING
}
async::CoroutineStarter DefaultInitializedContext::initAsync() {
return nullptr;
}
bool DefaultInitializedContext::isInitialized() const {
return true;
}
StreamType DefaultInitializedContext::getStreamType() const {
return m_streamType;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// IOStream
void IOStream::initContexts() {
auto& inStreamContext = getInputStreamContext();
if (!inStreamContext.isInitialized()) {
inStreamContext.init();
}
auto& outStreamContext = getOutputStreamContext();
if(outStreamContext != inStreamContext && !outStreamContext.isInitialized()) {
outStreamContext.init();
}
}
/**
* Init input/output stream contexts in an async manner.
*/
async::CoroutineStarter IOStream::initContextsAsync() {
async::CoroutineStarter starter(nullptr);
auto& inStreamContext = getInputStreamContext();
if (!inStreamContext.isInitialized()) {
starter.next(inStreamContext.initAsync());
}
auto& outStreamContext = getOutputStreamContext();
if(outStreamContext != inStreamContext && !outStreamContext.isInitialized()) {
starter.next(outStreamContext.initAsync());
}
return starter;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ConsistentOutputStream
v_io_size ConsistentOutputStream::writeAsString(v_int8 value){
v_char8 a[16];
auto size = utils::conversion::int32ToCharSequence(value, &a[0], 16);
if(size > 0){
return writeSimple(&a[0], size);
}
return 0;
}
v_io_size ConsistentOutputStream::writeAsString(v_uint8 value){
v_char8 a[16];
auto size = utils::conversion::uint32ToCharSequence(value, &a[0], 16);
if(size > 0){
return writeSimple(&a[0], size);
}
return 0;
}
v_io_size ConsistentOutputStream::writeAsString(v_int16 value){
v_char8 a[16];
auto size = utils::conversion::int32ToCharSequence(value, &a[0], 16);
if(size > 0){
return writeSimple(&a[0], size);
}
return 0;
}
v_io_size ConsistentOutputStream::writeAsString(v_uint16 value){
v_char8 a[16];
auto size = utils::conversion::uint32ToCharSequence(value, &a[0], 16);
if(size > 0){
return writeSimple(&a[0], size);
}
return 0;
}
v_io_size ConsistentOutputStream::writeAsString(v_int32 value){
v_char8 a[16];
auto size = utils::conversion::int32ToCharSequence(value, &a[0], 16);
if(size > 0){
return writeSimple(&a[0], size);
}
return 0;
}
v_io_size ConsistentOutputStream::writeAsString(v_uint32 value){
v_char8 a[16];
auto size = utils::conversion::uint32ToCharSequence(value, &a[0], 16);
if(size > 0){
return writeSimple(&a[0], size);
}
return 0;
}
v_io_size ConsistentOutputStream::writeAsString(v_int64 value){
v_char8 a[32];
auto size = utils::conversion::int64ToCharSequence(value, &a[0], 32);
if(size > 0){
return writeSimple(&a[0], size);
}
return 0;
}
v_io_size ConsistentOutputStream::writeAsString(v_uint64 value){
v_char8 a[32];
auto size = utils::conversion::uint64ToCharSequence(value, &a[0], 32);
if(size > 0){
return writeSimple(&a[0], size);
}
return 0;
}
v_io_size ConsistentOutputStream::writeAsString(v_float32 value){
v_char8 a[100];
auto size = utils::conversion::float32ToCharSequence(value, &a[0], 100);
if(size > 0){
return writeSimple(&a[0], size);
}
return 0;
}
v_io_size ConsistentOutputStream::writeAsString(v_float64 value){
v_char8 a[100];
auto size = utils::conversion::float64ToCharSequence(value, &a[0], 100);
if(size > 0){
return writeSimple(&a[0], size);
}
return 0;
}
v_io_size ConsistentOutputStream::writeAsString(bool value) {
if(value){
return writeSimple("true", 4);
} else {
return writeSimple("false", 5);
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Other functions
ConsistentOutputStream& operator << (ConsistentOutputStream& s, const oatpp::String& str) {
if(str) {
s.writeSimple(str);
} else {
s.writeSimple("[<String(null)>]");
}
return s;
}
ConsistentOutputStream& operator << (ConsistentOutputStream& s, const Int8& value) {
if(value.getPtr()) {
return operator << (s, *value);
}
s.writeSimple("[<Int8(null)>]");
return s;
}
ConsistentOutputStream& operator << (ConsistentOutputStream& s, const UInt8& value) {
if(value.getPtr()) {
return operator << (s, *value);
}
s.writeSimple("[<UInt8(null)>]");
return s;
}
ConsistentOutputStream& operator << (ConsistentOutputStream& s, const Int16& value) {
if(value.getPtr()) {
return operator << (s, *value);
}
s.writeSimple("[<Int16(null)>]");
return s;
}
ConsistentOutputStream& operator << (ConsistentOutputStream& s, const UInt16& value) {
if(value.getPtr()) {
return operator << (s, *value);
}
s.writeSimple("[<UInt16(null)>]");
return s;
}
ConsistentOutputStream& operator << (ConsistentOutputStream& s, const Int32& value) {
if(value.getPtr()) {
return operator << (s, *value);
}
s.writeSimple("[<Int32(null)>]");
return s;
}
ConsistentOutputStream& operator << (ConsistentOutputStream& s, const UInt32& value) {
if(value.getPtr()) {
return operator << (s, *value);
}
s.writeSimple("[<UInt32(null)>]");
return s;
}
ConsistentOutputStream& operator << (ConsistentOutputStream& s, const Int64& value) {
if(value.getPtr()) {
return operator << (s, *value);
}
s.writeSimple("[<Int64(null)>]");
return s;
}
ConsistentOutputStream& operator << (ConsistentOutputStream& s, const UInt64& value) {
if(value.getPtr()) {
return operator << (s, *value);
}
s.writeSimple("[<UInt64(null)>]");
return s;
}
ConsistentOutputStream& operator << (ConsistentOutputStream& s, const Float32& value) {
if(value.getPtr()) {
return operator << (s, *value);
}
s.writeSimple("[<Float32(null)>]");
return s;
}
ConsistentOutputStream& operator << (ConsistentOutputStream& s, const Float64& value) {
if(value.getPtr()) {
return operator << (s, *value);
}
s.writeSimple("[<Float64(null)>]");
return s;
}
ConsistentOutputStream& operator << (ConsistentOutputStream& s, const Boolean& value) {
if(value.getPtr()) { // use getPtr() here to avoid false to nullptr conversion
return operator << (s, *value);
}
s.writeSimple("[<Boolean(null)>]");
return s;
}
ConsistentOutputStream& operator << (ConsistentOutputStream& s, const char* str) {
if(str != nullptr) {
s.writeSimple(str);
} else {
s.writeSimple("[<char*(null)>]");
}
return s;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// DataTransferProcessor
StatelessDataTransferProcessor StatelessDataTransferProcessor::INSTANCE;
v_io_size StatelessDataTransferProcessor::suggestInputStreamReadSize() {
return 32767;
}
v_int32 StatelessDataTransferProcessor::iterate(data::buffer::InlineReadData& dataIn, data::buffer::InlineReadData& dataOut) {
if(dataOut.bytesLeft > 0) {
return Error::FLUSH_DATA_OUT;
}
if(dataIn.currBufferPtr != nullptr) {
if(dataIn.bytesLeft == 0){
return Error::PROVIDE_DATA_IN;
}
dataOut = dataIn;
dataIn.setEof();
return Error::FLUSH_DATA_OUT;
}
dataOut = dataIn;
dataIn.setEof();
return Error::FINISHED;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Other functions
v_io_size transfer(const base::ObjectHandle<ReadCallback>& readCallback,
const base::ObjectHandle<WriteCallback>& writeCallback,
v_io_size transferSize,
void* buffer,
v_buff_size bufferSize,
const base::ObjectHandle<data::buffer::Processor>& processor)
{
data::buffer::InlineReadData inData;
data::buffer::InlineReadData outData;
v_int32 procRes = data::buffer::Processor::Error::PROVIDE_DATA_IN;
v_io_size progress = 0;
while(procRes != data::buffer::Processor::Error::FINISHED) {
if(procRes == data::buffer::Processor::Error::PROVIDE_DATA_IN && inData.bytesLeft == 0) {
v_buff_size desiredToRead = processor->suggestInputStreamReadSize();
if (desiredToRead > bufferSize) {
desiredToRead = bufferSize;
}
if(transferSize > 0 && progress + desiredToRead > transferSize) {
desiredToRead = transferSize - progress;
}
v_io_size res = 0;
if(desiredToRead > 0) {
res = IOError::RETRY_READ;
while (res == IOError::RETRY_READ || res == IOError::RETRY_WRITE) {
res = readCallback->readSimple(buffer, desiredToRead);
}
}
if (res > 0) {
inData.set(buffer, res);
progress += res;
} else {
inData.set(nullptr, 0);
}
}
procRes = data::buffer::Processor::Error::OK;
while(procRes == data::buffer::Processor::Error::OK) {
procRes = processor->iterate(inData, outData);
}
switch(procRes) {
case data::buffer::Processor::Error::PROVIDE_DATA_IN: {
continue;
}
case data::buffer::Processor::Error::FLUSH_DATA_OUT: {
v_io_size res = IOError::RETRY_WRITE;
while(res == IOError::RETRY_WRITE || res == IOError::RETRY_READ) {
res = writeCallback->writeSimple(outData.currBufferPtr, outData.bytesLeft);
}
if(res > 0) {
outData.inc(res);
} else {
return progress;
}
break;
}
case data::buffer::Processor::Error::FINISHED:
return progress;
default:
//throw std::runtime_error("Unknown buffer processor error.");
return progress;
}
}
return progress;
}
async::CoroutineStarter transferAsync(const base::ObjectHandle<ReadCallback>& readCallback,
const base::ObjectHandle<WriteCallback>& writeCallback,
v_buff_size transferSize,
const base::ObjectHandle<data::buffer::IOBuffer>& buffer,
const base::ObjectHandle<data::buffer::Processor>& processor)
{
class TransferCoroutine : public oatpp::async::Coroutine<TransferCoroutine> {
private:
base::ObjectHandle<ReadCallback> m_readCallback;
base::ObjectHandle<WriteCallback> m_writeCallback;
v_buff_size m_transferSize;
base::ObjectHandle<oatpp::data::buffer::IOBuffer> m_buffer;
base::ObjectHandle<data::buffer::Processor> m_processor;
private:
v_buff_size m_progress;
private:
v_int32 m_procRes;
data::buffer::InlineReadData m_readData;
data::buffer::InlineWriteData m_writeData;
data::buffer::InlineReadData m_inData;
data::buffer::InlineReadData m_outData;
public:
TransferCoroutine(const base::ObjectHandle<ReadCallback>& readCallback,
const base::ObjectHandle<WriteCallback>& writeCallback,
v_buff_size transferSize,
const base::ObjectHandle<buffer::IOBuffer>& buffer,
const base::ObjectHandle<buffer::Processor>& processor)
: m_readCallback(readCallback)
, m_writeCallback(writeCallback)
, m_transferSize(transferSize)
, m_buffer(buffer)
, m_processor(processor)
, m_progress(0)
, m_procRes(data::buffer::Processor::Error::PROVIDE_DATA_IN)
, m_readData(buffer->getData(), buffer->getSize())
{}
Action act() override {
if(m_procRes == data::buffer::Processor::Error::FINISHED) {
return finish();
}
if(m_procRes == data::buffer::Processor::Error::PROVIDE_DATA_IN && m_inData.bytesLeft == 0) {
auto desiredToRead = m_processor->suggestInputStreamReadSize();
if (desiredToRead > m_readData.bytesLeft) {
desiredToRead = m_readData.bytesLeft;
}
if(m_transferSize > 0 && m_progress + desiredToRead > m_transferSize) {
desiredToRead = m_transferSize - m_progress;
}
Action action;
v_io_size res = 0;
if(desiredToRead > 0) {
res = m_readCallback->read(m_readData.currBufferPtr, desiredToRead, action);
}
if (res > 0) {
m_readData.inc(res);
m_inData.set(m_buffer->getData(), m_buffer->getSize() - m_readData.bytesLeft);
m_progress += res;
} else {
switch(res) {
case IOError::BROKEN_PIPE:
if(m_transferSize > 0) {
return error<AsyncTransferError>("[oatpp::data::stream::transferAsync]: Error. ReadCallback. BROKEN_PIPE.");
}
m_inData.set(nullptr, 0);
break;
case IOError::ZERO_VALUE:
m_inData.set(nullptr, 0);
break;
case IOError::RETRY_READ:
if(!action.isNone()) {
return action;
}
return repeat();
case IOError::RETRY_WRITE:
if(!action.isNone()) {
return action;
}
return repeat();
default:
if(m_transferSize > 0) {
if (!action.isNone()) {
return action;
}
return error<AsyncTransferError>("[oatpp::data::stream::transferAsync]: Error. ReadCallback. Unknown IO error.");
}
m_inData.set(nullptr, 0);
}
}
if(!action.isNone()){
return action;
}
}
return yieldTo(&TransferCoroutine::process);
}
Action process() {
m_procRes = m_processor->iterate(m_inData, m_outData);
switch(m_procRes) {
case data::buffer::Processor::Error::OK:
return repeat();
case data::buffer::Processor::Error::PROVIDE_DATA_IN: {
m_readData.set(m_buffer->getData(), m_buffer->getSize());
return yieldTo(&TransferCoroutine::act);
}
case data::buffer::Processor::Error::FLUSH_DATA_OUT: {
m_readData.set(m_buffer->getData(), m_buffer->getSize());
m_writeData.set(m_outData.currBufferPtr, m_outData.bytesLeft);
m_outData.setEof();
return yieldTo(&TransferCoroutine::flushData);
}
case data::buffer::Processor::Error::FINISHED:
return finish();
default:
return error<AsyncTransferError>("[oatpp::data::stream::transferAsync]: Error. ReadCallback. Unknown processing error.");
}
}
Action flushData() {
return m_writeCallback->writeExactSizeDataAsyncInline(m_writeData, yieldTo(&TransferCoroutine::act));
}
};
return TransferCoroutine::start(readCallback, writeCallback, transferSize, buffer, processor);
}
}}}
| vincent-in-black-sesame/oat | src/oatpp/core/data/stream/Stream.cpp | C++ | apache-2.0 | 24,461 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef oatpp_data_Stream
#define oatpp_data_Stream
#include "oatpp/core/data/share/LazyStringMap.hpp"
#include "oatpp/core/async/Coroutine.hpp"
#include "oatpp/core/data/buffer/IOBuffer.hpp"
#include "oatpp/core/data/buffer/Processor.hpp"
#include "oatpp/core/IODefinitions.hpp"
namespace oatpp { namespace data{ namespace stream {
/**
* Stream Type.
*/
enum StreamType : v_int32 {
/**
* Finite stream.
*/
STREAM_FINITE = 0,
/**
* Infinite stream.
*/
STREAM_INFINITE = 1
};
/**
* Stream Context.
*/
class Context {
public:
/**
* Convenience typedef for &id:oatpp::data::share::LazyStringMap;.
*/
typedef oatpp::data::share::LazyStringMap<oatpp::data::share::StringKeyLabel> Properties;
private:
Properties m_properties;
protected:
/**
* `protected`. Get mutable additional optional context specific properties.
* @return - &l:Context::Properties;.
*/
Properties& getMutableProperties();
public:
/**
* Default constructor.
*/
Context() = default;
/**
* Constructor.
* @param properties - &l:Context::Properties;.
*/
Context(Properties&& properties);
/**
* Virtual destructor.
*/
virtual ~Context() = default;
/**
* Initialize stream context.
*/
virtual void init() = 0;
/**
* Initialize stream context in an async manner.
* @return - &id:oatpp::async::CoroutineStarter;.
*/
virtual async::CoroutineStarter initAsync() = 0;
/**
* Check if the stream context is initialized.
* @return - `bool`.
*/
virtual bool isInitialized() const = 0;
/**
* Get stream type.
* @return - &l:StreamType;.
*/
virtual StreamType getStreamType() const = 0;
/**
* Additional optional context specific properties.
* @return - &l:Context::Properties;.
*/
const Properties& getProperties() const;
inline bool operator == (const Context& other){
return this == &other;
}
inline bool operator != (const Context& other){
return this != &other;
}
};
/**
* The default implementation for context with no initialization.
*/
class DefaultInitializedContext : public oatpp::data::stream::Context {
private:
StreamType m_streamType;
public:
/**
* Constructor.
* @param streamType - &l:StreamType;.
*/
DefaultInitializedContext(StreamType streamType);
/**
* Constructor.
* @param streamType - &l:StreamType;.
* @param properties - &l:Context::Properties;.
*/
DefaultInitializedContext(StreamType streamType, Properties&& properties);
/**
* Initialize stream context. <br>
* *This particular implementation does nothing.*
*/
void init() override;
/**
* Initialize stream context in an async manner.
* *This particular implementation does nothing.*
* @return - &id:oatpp::async::CoroutineStarter;.
*/
async::CoroutineStarter initAsync() override;
/**
* Check if the stream context is initialized.
* *This particular implementation always returns `true`.*
* @return - `bool`.
*/
bool isInitialized() const override;
/**
* Get stream type.
* @return - &l:StreamType;.
*/
StreamType getStreamType() const override;
};
/**
* Stream I/O mode.
*/
enum IOMode : v_int32 {
/**
* Blocking stream I/O mode.
*/
BLOCKING = 0,
/**
* Non-blocking stream I/O mode.
*/
ASYNCHRONOUS = 1
};
/**
* Callback for stream write operation.
*/
class WriteCallback {
public:
/**
* Default virtual destructor.
*/
virtual ~WriteCallback() = default;
/**
* Write operation callback.
* @param data - pointer to data.
* @param count - size of the data in bytes.
* @param action - async specific action. If action is NOT &id:oatpp::async::Action::TYPE_NONE;, then
* caller MUST return this action on coroutine iteration.
* @return - actual number of bytes written. 0 - to indicate end-of-file.
*/
virtual v_io_size write(const void *data, v_buff_size count, async::Action& action) = 0;
v_io_size write(data::buffer::InlineWriteData& inlineData, async::Action& action);
v_io_size writeSimple(const void *data, v_buff_size count);
v_io_size writeExactSizeDataSimple(data::buffer::InlineWriteData& inlineData);
v_io_size writeExactSizeDataSimple(const void *data, v_buff_size count);
async::Action writeExactSizeDataAsyncInline(data::buffer::InlineWriteData& inlineData, async::Action&& nextAction);
async::CoroutineStarter writeExactSizeDataAsync(const void* data, v_buff_size size);
/**
* Same as `write((p_char8)data, std::strlen(data));`.
* @param data - data to write.
* @return - actual number of bytes written. &id:oatpp::v_io_size;.
*/
v_io_size writeSimple(const char* data){
return writeSimple((p_char8)data, std::strlen(data));
}
/**
* Same as `write(str->getData(), str->getSize());`
* @param str - data to write.
* @return - actual number of bytes written. &id:oatpp::v_io_size;.
*/
v_io_size writeSimple(const oatpp::String& str){
return writeSimple(str->data(), str->size());
}
/**
* Same as `write(&c, 1);`.
* @param c - one char to write.
* @return - actual number of bytes written. &id:oatpp::v_io_size;.
*/
v_io_size writeCharSimple(v_char8 c){
return writeSimple(&c, 1);
}
};
/**
* Output Stream.
*/
class OutputStream : public WriteCallback {
public:
/**
* Default virtual destructor.
*/
virtual ~OutputStream() = default;
/**
* Set stream I/O mode.
* @throws
*/
virtual void setOutputStreamIOMode(IOMode ioMode) = 0;
/**
* Get stream I/O mode.
* @return
*/
virtual IOMode getOutputStreamIOMode() = 0;
/**
* Get stream context.
* @return - &l:Context;.
*/
virtual Context& getOutputStreamContext() = 0;
};
/**
* Stream read callback.
*/
class ReadCallback {
public:
/**
* Default virtual destructor.
*/
virtual ~ReadCallback() = default;
/**
* Read operation callback.
* @param buffer - pointer to buffer.
* @param count - size of the buffer in bytes.
* @param action - async specific action. If action is NOT &id:oatpp::async::Action::TYPE_NONE;, then
* caller MUST return this action on coroutine iteration.
* @return - actual number of bytes written to buffer. 0 - to indicate end-of-file.
*/
virtual v_io_size read(void *buffer, v_buff_size count, async::Action& action) = 0;
v_io_size read(data::buffer::InlineReadData& inlineData, async::Action& action);
v_io_size readExactSizeDataSimple(data::buffer::InlineReadData& inlineData);
v_io_size readExactSizeDataSimple(void *data, v_buff_size count);
async::Action readExactSizeDataAsyncInline(data::buffer::InlineReadData& inlineData, async::Action&& nextAction);
async::Action readSomeDataAsyncInline(data::buffer::InlineReadData& inlineData, async::Action&& nextAction);
v_io_size readSimple(void *data, v_buff_size count);
};
/**
* Input Stream.
*/
class InputStream : public ReadCallback {
public:
/**
* Default virtual destructor.
*/
virtual ~InputStream() = default;
/**
* Set stream I/O mode.
* @throws
*/
virtual void setInputStreamIOMode(IOMode ioMode) = 0;
/**
* Get stream I/O mode.
* @return
*/
virtual IOMode getInputStreamIOMode() = 0;
/**
* Get stream context.
* @return - &l:Context;.
*/
virtual Context& getInputStreamContext() = 0;
};
/**
* Buffered Input Stream
*/
class BufferedInputStream : public InputStream {
public:
/**
* Default virtual destructor.
*/
virtual ~BufferedInputStream() = default;
/**
* Peek up to count of bytes int he buffer
* @param data
* @param count
* @return [1..count], IOErrors.
*/
virtual v_io_size peek(void *data, v_buff_size count, async::Action& action) = 0;
/**
* Amount of bytes currently available to read from buffer.
* @return &id:oatpp::v_io_size;.
*/
virtual v_io_size availableToRead() const = 0;
/**
* Commit read offset
* @param count
* @return [1..count], IOErrors.
*/
virtual v_io_size commitReadOffset(v_buff_size count) = 0;
};
/**
* I/O Stream.
*/
class IOStream : public InputStream, public OutputStream {
public:
/**
* Init input/output stream contexts.
*/
void initContexts();
/**
* Init input/output stream contexts in an async manner.
*/
async::CoroutineStarter initContextsAsync();
};
/**
* Streams that guarantee data to be written in exact amount as specified in call to &l:OutputStream::write (); should extend this class.
*/
class ConsistentOutputStream : public OutputStream {
public:
/**
* Convert value to string and write to stream.
* @param value
* @return - actual number of bytes written. &id:oatpp::v_io_size;. <br>
*/
v_io_size writeAsString(v_int8 value);
/**
* Convert value to string and write to stream.
* @param value
* @return - actual number of bytes written. &id:oatpp::v_io_size;. <br>
*/
v_io_size writeAsString(v_uint8 value);
/**
* Convert value to string and write to stream.
* @param value
* @return - actual number of bytes written. &id:oatpp::v_io_size;. <br>
*/
v_io_size writeAsString(v_int16 value);
/**
* Convert value to string and write to stream.
* @param value
* @return - actual number of bytes written. &id:oatpp::v_io_size;. <br>
*/
v_io_size writeAsString(v_uint16 value);
/**
* Convert value to string and write to stream.
* @param value
* @return - actual number of bytes written. &id:oatpp::v_io_size;. <br>
*/
v_io_size writeAsString(v_int32 value);
/**
* Convert value to string and write to stream.
* @param value
* @return - actual number of bytes written. &id:oatpp::v_io_size;. <br>
*/
v_io_size writeAsString(v_uint32 value);
/**
* Convert value to string and write to stream.
* @param value
* @return - actual number of bytes written. &id:oatpp::v_io_size;. <br>
*/
v_io_size writeAsString(v_int64 value);
/**
* Convert value to string and write to stream.
* @param value
* @return - actual number of bytes written. &id:oatpp::v_io_size;. <br>
*/
v_io_size writeAsString(v_uint64 value);
/**
* Convert value to string and write to stream.
* @param value
* @return - actual number of bytes written. &id:oatpp::v_io_size;. <br>
*/
v_io_size writeAsString(v_float32 value);
/**
* Convert value to string and write to stream.
* @param value
* @return - actual number of bytes written. &id:oatpp::v_io_size;. <br>
*/
v_io_size writeAsString(v_float64 value);
/**
* Convert value to string and write to stream.
* @param value
* @return - actual number of bytes written. &id:oatpp::v_io_size;. <br>
*/
v_io_size writeAsString(bool value);
};
ConsistentOutputStream& operator << (ConsistentOutputStream& s, const oatpp::String& str);
ConsistentOutputStream& operator << (ConsistentOutputStream& s, const Int8& value);
ConsistentOutputStream& operator << (ConsistentOutputStream& s, const UInt8& value);
ConsistentOutputStream& operator << (ConsistentOutputStream& s, const Int16& value);
ConsistentOutputStream& operator << (ConsistentOutputStream& s, const UInt16& value);
ConsistentOutputStream& operator << (ConsistentOutputStream& s, const Int32& value);
ConsistentOutputStream& operator << (ConsistentOutputStream& s, const UInt32& value);
ConsistentOutputStream& operator << (ConsistentOutputStream& s, const Int64& value);
ConsistentOutputStream& operator << (ConsistentOutputStream& s, const UInt64& value);
ConsistentOutputStream& operator << (ConsistentOutputStream& s, const Float32& value);
ConsistentOutputStream& operator << (ConsistentOutputStream& s, const Float64& value);
ConsistentOutputStream& operator << (ConsistentOutputStream& s, const Boolean& value);
ConsistentOutputStream& operator << (ConsistentOutputStream& s, const char* str);
template<typename T>
ConsistentOutputStream& operator << (ConsistentOutputStream& s, T value) {
s.writeAsString(value);
return s;
}
/**
* Error of Asynchronous stream transfer.
*/
class AsyncTransferError : public oatpp::async::Error {
public:
/**
* Constructor.
* @param what
*/
AsyncTransferError(const char* what) : oatpp::async::Error(what) {}
};
/**
* Plain data transfer processor.
* Transfers data as is.
*/
class StatelessDataTransferProcessor : public data::buffer::Processor {
public:
static StatelessDataTransferProcessor INSTANCE;
public:
v_io_size suggestInputStreamReadSize() override;
v_int32 iterate(data::buffer::InlineReadData& dataIn, data::buffer::InlineReadData& dataOut) override;
};
/**
* Transfer data from `readCallback` to `writeCallback`.
* @param readCallback - &l:ReadCallback;.
* @param writeCallback - &l:WriteCallback;.
* @param transferSize - how much data should be read from the `readCallback`. `0` - to read until error.
* @param buffer - pointer to buffer used to do the transfer by chunks.
* @param bufferSize - size of the buffer.
* @param processor - data processing to be applied during the transfer.
* @return - the actual amout of bytes read from the `readCallback`.
*/
v_io_size transfer(const base::ObjectHandle<ReadCallback>& readCallback,
const base::ObjectHandle<WriteCallback>& writeCallback,
v_io_size transferSize,
void* buffer,
v_buff_size bufferSize,
const base::ObjectHandle<data::buffer::Processor>& processor = &StatelessDataTransferProcessor::INSTANCE);
/**
* Transfer data from `readCallback` to `writeCallback` in Async manner.
* @param readCallback - &l:ReadCallback;.
* @param writeCallback - &l:WriteCallback;.
* @param transferSize - how much data should be read from the `readCallback`. `0` - to read until error.
* @param buffer - &id:oatpp::data::buffer::IOBuffer; used to do the transfer by chunks.
* @param processor - data processing to be applied during the transfer.
* @return - &id:oatpp::async::CoroutineStarter;.
*/
async::CoroutineStarter transferAsync(const base::ObjectHandle<ReadCallback>& readCallback,
const base::ObjectHandle<WriteCallback>& writeCallback,
v_buff_size transferSize,
const base::ObjectHandle<data::buffer::IOBuffer>& buffer,
const base::ObjectHandle<data::buffer::Processor>& processor = &StatelessDataTransferProcessor::INSTANCE);
}}}
#endif /* defined(_data_Stream) */
| vincent-in-black-sesame/oat | src/oatpp/core/data/stream/Stream.hpp | C++ | apache-2.0 | 15,535 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#include "StreamBufferedProxy.hpp"
namespace oatpp { namespace data{ namespace stream {
v_io_size OutputStreamBufferedProxy::write(const void *data, v_buff_size count, async::Action& action) {
if(m_buffer.availableToWrite() > 0) {
return m_buffer.write(data, count);
} else {
auto bytesFlushed = m_buffer.readAndWriteToStream(m_outputStream.get(), m_buffer.getBufferSize(), action);
if(bytesFlushed > 0) {
return m_buffer.write(data, count);
}
return bytesFlushed;
}
}
void OutputStreamBufferedProxy::setOutputStreamIOMode(oatpp::data::stream::IOMode ioMode) {
m_outputStream->setOutputStreamIOMode(ioMode);
}
oatpp::data::stream::IOMode OutputStreamBufferedProxy::getOutputStreamIOMode() {
return m_outputStream->getOutputStreamIOMode();
}
Context& OutputStreamBufferedProxy::getOutputStreamContext() {
return m_outputStream->getOutputStreamContext();
}
v_io_size OutputStreamBufferedProxy::flush() {
return m_buffer.flushToStream(m_outputStream.get());
}
oatpp::async::CoroutineStarter OutputStreamBufferedProxy::flushAsync() {
return m_buffer.flushToStreamAsync(m_outputStream);
}
v_io_size InputStreamBufferedProxy::read(void *data, v_buff_size count, async::Action& action) {
if(m_buffer.availableToRead() > 0) {
return m_buffer.read(data, count);
} else {
auto bytesBuffered = m_buffer.readFromStreamAndWrite(m_inputStream.get(), m_buffer.getBufferSize(), action);
if(bytesBuffered > 0) {
return m_buffer.read(data, count);
}
return bytesBuffered;
}
}
v_io_size InputStreamBufferedProxy::peek(void *data, v_buff_size count, async::Action& action) {
if(m_buffer.availableToRead() > 0) {
return m_buffer.peek(data, count);
} else {
auto bytesBuffered = m_buffer.readFromStreamAndWrite(m_inputStream.get(), m_buffer.getBufferSize(), action);
if(bytesBuffered > 0) {
return m_buffer.peek(data, count);
}
return bytesBuffered;
}
}
v_io_size InputStreamBufferedProxy::commitReadOffset(v_buff_size count) {
return m_buffer.commitReadOffset(count);
}
void InputStreamBufferedProxy::setInputStreamIOMode(oatpp::data::stream::IOMode ioMode) {
m_inputStream->setInputStreamIOMode(ioMode);
}
oatpp::data::stream::IOMode InputStreamBufferedProxy::getInputStreamIOMode() {
return m_inputStream->getInputStreamIOMode();
}
Context& InputStreamBufferedProxy::getInputStreamContext() {
return m_inputStream->getInputStreamContext();
}
v_io_size InputStreamBufferedProxy::availableToRead() const {
return m_buffer.availableToRead();
}
}}}
| vincent-in-black-sesame/oat | src/oatpp/core/data/stream/StreamBufferedProxy.cpp | C++ | apache-2.0 | 3,565 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef oatpp_data_stream_StreamBufferedProxy_hpp
#define oatpp_data_stream_StreamBufferedProxy_hpp
#include "Stream.hpp"
#include "oatpp/core/data/buffer/FIFOBuffer.hpp"
#include "oatpp/core/data/share/MemoryLabel.hpp"
#include "oatpp/core/async/Coroutine.hpp"
namespace oatpp { namespace data{ namespace stream {
class OutputStreamBufferedProxy : public oatpp::base::Countable, public OutputStream {
private:
std::shared_ptr<OutputStream> m_outputStream;
oatpp::data::share::MemoryLabel m_memoryLabel;
buffer::FIFOBuffer m_buffer;
public:
OutputStreamBufferedProxy(const std::shared_ptr<OutputStream>& outputStream,
const oatpp::data::share::MemoryLabel& memoryLabel)
: m_outputStream(outputStream)
, m_memoryLabel(memoryLabel)
, m_buffer((void *) memoryLabel.getData(), memoryLabel.getSize())
{}
public:
static std::shared_ptr<OutputStreamBufferedProxy> createShared(const std::shared_ptr<OutputStream>& outputStream, const oatpp::data::share::MemoryLabel& memoryLabel) {
return std::make_shared<OutputStreamBufferedProxy>(outputStream, memoryLabel);
}
v_io_size write(const void *data, v_buff_size count, async::Action& action) override;
/**
* Set OutputStream I/O mode.
* @param ioMode
*/
void setOutputStreamIOMode(oatpp::data::stream::IOMode ioMode) override;
/**
* Set OutputStream I/O mode.
* @return
*/
oatpp::data::stream::IOMode getOutputStreamIOMode() override;
/**
* Get context of the underlying stream.
* @return
*/
Context& getOutputStreamContext() override;
v_io_size flush();
oatpp::async::CoroutineStarter flushAsync();
void setBufferPosition(v_io_size readPosition, v_io_size writePosition, bool canRead) {
m_buffer.setBufferPosition(readPosition, writePosition, canRead);
}
};
class InputStreamBufferedProxy : public oatpp::base::Countable, public BufferedInputStream {
protected:
std::shared_ptr<InputStream> m_inputStream;
oatpp::data::share::MemoryLabel m_memoryLabel;
buffer::FIFOBuffer m_buffer;
public:
InputStreamBufferedProxy(const std::shared_ptr<InputStream>& inputStream,
const oatpp::data::share::MemoryLabel& memoryLabel,
v_io_size bufferReadPosition,
v_io_size bufferWritePosition,
bool bufferCanRead)
: m_inputStream(inputStream)
, m_memoryLabel(memoryLabel)
, m_buffer((void*) memoryLabel.getData(), memoryLabel.getSize(), bufferReadPosition, bufferWritePosition, bufferCanRead)
{}
public:
static std::shared_ptr<InputStreamBufferedProxy> createShared(const std::shared_ptr<InputStream>& inputStream,
const oatpp::data::share::MemoryLabel& memoryLabel)
{
return std::make_shared<InputStreamBufferedProxy>(inputStream, memoryLabel, 0, 0, false);
}
static std::shared_ptr<InputStreamBufferedProxy> createShared(const std::shared_ptr<InputStream>& inputStream,
const oatpp::data::share::MemoryLabel& memoryLabel,
v_io_size bufferReadPosition,
v_io_size bufferWritePosition,
bool bufferCanRead)
{
return std::make_shared<InputStreamBufferedProxy>(inputStream, memoryLabel, bufferReadPosition, bufferWritePosition, bufferCanRead);
}
v_io_size read(void *data, v_buff_size count, async::Action& action) override;
v_io_size peek(void *data, v_buff_size count, async::Action& action) override;
v_io_size commitReadOffset(v_buff_size count) override;
v_io_size availableToRead() const override;
/**
* Set InputStream I/O mode.
* @param ioMode
*/
void setInputStreamIOMode(oatpp::data::stream::IOMode ioMode) override;
/**
* Get InputStream I/O mode.
* @return
*/
oatpp::data::stream::IOMode getInputStreamIOMode() override;
/**
* Get context of the underlying stream.
* @return
*/
Context& getInputStreamContext() override;
void setBufferPosition(v_io_size readPosition, v_io_size writePosition, bool canRead) {
m_buffer.setBufferPosition(readPosition, writePosition, canRead);
}
};
}}}
#endif /* oatpp_data_stream_StreamBufferedProxy_hpp */
| vincent-in-black-sesame/oat | src/oatpp/core/data/stream/StreamBufferedProxy.hpp | C++ | apache-2.0 | 5,448 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
/**[info]
* This file contains source code for basic helper macros used for code-generator.
*/
#ifndef oatpp_macro_basic_hpp
#define oatpp_macro_basic_hpp
#define OATPP_MACRO_FOREACH_EXAMPLE_FUNC(INDEX, COUNT, X) \
ENV::log("macro", "param: %d/%d: '%s'", INDEX, COUNT, #X);
#define OATPP_MACRO_FOREACH_EXAMPLE(...) OATPP_MACRO_FOREACH(OATPP_MACRO_FOREACH_EXAMPLE_FUNC, (__VA_ARGS__))
#define OATPP_MACRO__NUM_ARGS(X64, X63, X62, X61, X60, X59, X58, X57, X56, X55, X54, X53, X52, X51, X50, X49, X48, X47, X46, X45, X44, X43, X42, X41, X40, X39, X38, X37, X36, X35, X34, X33, X32, X31, X30, X29, X28, X27, X26, X25, X24, X23, X22, X21, X20, X19, X18, X17, X16, X15, X14, X13, X12, X11, X10, X9, X8, X7, X6, X5, X4, X3, X2, X1, N, ...) N
#define OATPP_MACRO_NUM_ARGS(...) OATPP_MACRO_EXPAND(OATPP_MACRO__NUM_ARGS(__VA_ARGS__, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1))
#define OATPP_MACRO_HAS_ARGS_ARR(...) OATPP_MACRO_EXPAND(OATPP_MACRO__NUM_ARGS(__VA_ARGS__, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0))
//////////////////////////////////////////////////////////////////////
#define OATPP_MACRO_CONCAT(X,Y) OATPP_MACRO_CONCAT(X,Y)
#define OATPP_MACRO_CONCAT2(X,Y) X##Y
#define OATPP_MACRO_CONCAT_2 OATPP_MACRO_CONCAT
#define OATPP_MACRO_CONCAT_3(X,Y,Z) OATPP_MACRO_CONCAT(X,OATPP_MACRO_CONCAT(Y,Z))
#define OATPP_MACRO_STR(X) #X
#define OATPP_MACRO_EXPAND(X) X
#define OATPP_MACRO_FIRSTARG(X, ...) X
#define OATPP_MACRO_SECONDARG(X, Y, ...) Y
#define OATPP_MACRO_FIRSTARG_STR(X, ...) #X
#define OATPP_MACRO_RESTARGS(X, ...) __VA_ARGS__
#define OATPP_MACRO_FIRSTARG_EXPAND(X, ...) X
#define OATPP_MACRO_UNFOLD_VA_ARGS(...) __VA_ARGS__
/////////
#define OATPP_MACRO_MACRO_SELECTOR_CALL(X, Y) OATPP_MACRO_CONCAT2(X, Y)
#define OATPP_MACRO_MACRO_SELECTOR(MACRO, PARAMS_LIST) OATPP_MACRO_MACRO_SELECTOR_CALL(MACRO, OATPP_MACRO_NUM_ARGS PARAMS_LIST)
#define OATPP_MACRO_MACRO_BINARY_SELECTOR(MACRO, PARAMS_LIST) OATPP_MACRO_MACRO_SELECTOR_CALL(MACRO, OATPP_MACRO_HAS_ARGS_ARR PARAMS_LIST)
/////////
#define OATPP_MACRO_FOREACH_OR_EMPTY_0(MACRO)
#define OATPP_MACRO_FOREACH_OR_EMPTY_1(MACRO, ...) OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH(MACRO, __VA_ARGS__))
/*
* @param MACRO
* @param LIST_OF_PARAMETERS
*/
#define OATPP_MACRO_FOREACH_OR_EMPTY(...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_MACRO_BINARY_SELECTOR(OATPP_MACRO_FOREACH_OR_EMPTY_, (__VA_ARGS__)) (__VA_ARGS__))
//
#define OATPP_MACRO_FOREACH_FIRST_AND_REST_0(FIRST_MACRO, MACRO, FIRST_ARG) \
FIRST_MACRO(0, 0, FIRST_ARG)
#define OATPP_MACRO_FOREACH_FIRST_AND_REST_1(FIRST_MACRO, MACRO, FIRST_ARG, ...) \
OATPP_MACRO_EXPAND(FIRST_MACRO(0, 0, FIRST_ARG) OATPP_MACRO_FOREACH(MACRO, __VA_ARGS__))
/*
* @param FIRST_MACRO
* @param MACRO
* @param LIST_OF_PARAMETERS
*/
#define OATPP_MACRO_FOREACH_FIRST_AND_REST(FIRST_MACRO, MACRO, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_MACRO_BINARY_SELECTOR(OATPP_MACRO_FOREACH_FIRST_AND_REST_, (__VA_ARGS__)) (FIRST_MACRO, MACRO, __VA_ARGS__))
/////////
#define OATPP_MACRO_FOREACH(MACRO, ...) OATPP_MACRO_FOREACH_(OATPP_MACRO_NUM_ARGS(__VA_ARGS__), MACRO, __VA_ARGS__)
#define OATPP_MACRO_FOREACH_(N, M, ...) OATPP_MACRO_FOREACH__(N, M, __VA_ARGS__)
#define OATPP_MACRO_FOREACH__(N, M, ...) OATPP_MACRO_FOREACH_##N(N, M, __VA_ARGS__)
#define OATPP_MACRO_FOREACH_CALL(INDEX, COUNT, MACRO, PARAM) MACRO(INDEX, COUNT, PARAM)
#define OATPP_MACRO_FOREACH_1(N, M, ...) OATPP_MACRO_FOREACH_CALL(N - 1, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_2(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 2, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_1(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_3(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 3, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_2(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_4(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 4, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_3(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_5(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 5, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_4(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_6(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 6, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_5(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_7(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 7, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_6(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_8(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 8, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_7(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_9(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 9, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_8(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_10(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 10, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_9(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_11(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 11, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_10(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_12(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 12, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_11(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_13(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 13, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_12(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_14(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 14, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_13(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_15(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 15, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_14(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_16(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 16, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_15(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_17(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 17, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_16(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_18(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 18, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_17(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_19(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 19, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_18(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_20(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 20, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_19(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_21(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 21, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_20(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_22(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 22, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_21(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_23(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 23, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_22(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_24(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 24, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_23(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_25(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 25, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_24(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_26(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 26, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_25(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_27(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 27, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_26(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_28(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 28, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_27(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_29(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 29, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_28(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_30(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 30, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_29(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_31(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 31, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_30(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_32(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 32, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_31(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_33(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 33, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_32(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_34(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 34, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_33(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_35(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 35, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_34(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_36(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 36, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_35(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_37(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 37, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_36(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_38(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 38, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_37(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_39(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 39, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_38(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_40(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 40, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_39(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_41(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 41, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_40(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_42(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 42, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_41(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_43(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 43, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_42(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_44(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 44, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_43(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_45(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 45, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_44(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_46(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 46, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_45(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_47(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 47, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_46(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_48(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 48, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_47(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_49(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 49, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_48(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_50(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 50, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_49(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_51(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 51, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_50(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_52(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 52, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_51(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_53(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 53, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_52(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_54(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 54, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_53(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_55(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 55, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_54(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_56(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 56, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_55(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_57(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 57, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_56(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_58(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 58, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_57(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_59(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 59, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_58(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_60(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 60, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_59(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_61(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 61, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_60(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_62(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 62, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_61(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_63(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 63, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_62(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_64(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 64, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_63(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_65(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 65, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_64(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_66(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 66, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_65(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_67(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 67, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_66(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_68(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 68, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_67(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_69(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 69, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_68(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_70(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 70, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_69(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_71(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 71, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_70(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_72(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 72, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_71(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_73(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 73, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_72(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_74(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 74, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_73(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_75(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 75, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_74(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_76(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 76, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_75(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_77(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 77, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_76(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_78(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 78, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_77(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_79(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 79, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_78(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_80(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 80, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_79(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_81(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 81, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_80(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_82(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 82, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_81(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_83(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 83, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_82(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_84(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 84, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_83(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_85(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 85, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_84(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_86(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 86, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_85(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_87(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 87, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_86(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_88(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 88, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_87(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_89(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 89, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_88(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_90(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 90, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_89(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_91(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 91, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_90(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_92(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 92, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_91(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_93(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 93, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_92(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_94(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 94, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_93(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_95(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 95, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_94(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_96(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 96, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_95(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_97(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 97, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_96(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_98(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 98, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_97(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#define OATPP_MACRO_FOREACH_99(N, M, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_FOREACH_CALL(N - 99, N, M, OATPP_MACRO_FIRSTARG_EXPAND(__VA_ARGS__))) \
OATPP_MACRO_FOREACH_98(N, M, OATPP_MACRO_RESTARGS(__VA_ARGS__))
#endif /* oatpp_macro_basic_hpp */
| vincent-in-black-sesame/oat | src/oatpp/core/macro/basic.hpp | C++ | apache-2.0 | 25,691 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
/**[info]
* This file contains source code for `OATPP_CODEGEN_BEGIN(NAME)` and `OATPP_CODEGEN_END(NAME)` macros. <br>
* <br>
*
* More about use of `OATPP_CODEGEN_BEGIN` and `OATPP_CODEGEN_BEGIN` see: <br>
* <ul>
* <li>[ApiController component](https://oatpp.io/docs/components/api-controller/)</li>
* <li>[ApiClient component](https://oatpp.io/docs/components/api-client/)</li>
* <li>[Data Transfer Object(DTO) component](https://oatpp.io/docs/components/dto/)</li>
* </ul>
*
*/
#ifndef oatpp_macro_codegen_hpp
#define oatpp_macro_codegen_hpp
#include "./basic.hpp"
#define OATPP_CODEGEN_DEFINE_ApiClient "oatpp/codegen/ApiClient_define.hpp"
#define OATPP_CODEGEN_UNDEF_ApiClient "oatpp/codegen/ApiClient_undef.hpp"
#define OATPP_CODEGEN_DEFINE_ApiController "oatpp/codegen/ApiController_define.hpp"
#define OATPP_CODEGEN_UNDEF_ApiController "oatpp/codegen/ApiController_undef.hpp"
#define OATPP_CODEGEN_DEFINE_DbClient "oatpp/codegen/DbClient_define.hpp"
#define OATPP_CODEGEN_UNDEF_DbClient "oatpp/codegen/DbClient_undef.hpp"
#define OATPP_CODEGEN_DEFINE_DTO "oatpp/codegen/DTO_define.hpp"
#define OATPP_CODEGEN_UNDEF_DTO "oatpp/codegen/DTO_undef.hpp"
#define OATPP_CODEGEN_BEGIN(NAME) OATPP_MACRO_EXPAND(OATPP_CODEGEN_DEFINE_ ## NAME)
#define OATPP_CODEGEN_END(NAME) OATPP_MACRO_EXPAND(OATPP_CODEGEN_UNDEF_ ## NAME)
#endif /* oatpp_macro_codegen_hpp */
| vincent-in-black-sesame/oat | src/oatpp/core/macro/codegen.hpp | C++ | apache-2.0 | 2,377 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
/**[info]
* This file contains source code for `OATPP_CREATE_COMPONENT` and `OATPP_COMPONENT` macros which are part of
* oatpp Dependency Injection (DI) framework. <br>
* <br>
* For usage examples see example-projects:
* <ul>
* <li>[CRUD - example](https://github.com/oatpp/example-crud)</li>
* <li>[HLS Media Stream - example](https://github.com/oatpp/example-hls-media-stream)</li>
* <li>[Async API - example](https://github.com/oatpp/example-async-api)</li>
* </ul>
*/
#ifndef oatpp_macro_component_hpp
#define oatpp_macro_component_hpp
#include "./basic.hpp"
#include "oatpp/core/base/Environment.hpp"
#define OATPP_MACRO_GET_COMPONENT_1(TYPE) \
(*((TYPE*) oatpp::base::Environment::getComponent(typeid(TYPE).name())))
#define OATPP_MACRO_GET_COMPONENT_2(TYPE, QUALIFIER) \
(*((TYPE*) oatpp::base::Environment::getComponent(typeid(TYPE).name(), QUALIFIER)))
#define OATPP_GET_COMPONENT(...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_MACRO_SELECTOR(OATPP_MACRO_GET_COMPONENT_, (__VA_ARGS__)) (__VA_ARGS__))
#define OATPP_MACRO_COMPONENT_1(TYPE, NAME) \
TYPE& NAME = (*((TYPE*) oatpp::base::Environment::getComponent(typeid(TYPE).name())))
#define OATPP_MACRO_COMPONENT_2(TYPE, NAME, QUALIFIER) \
TYPE& NAME = (*((TYPE*) oatpp::base::Environment::getComponent(typeid(TYPE).name(), QUALIFIER)))
/**
* Inject component. Create variable of type=TYPE and name=NAME and assign registered component to it.
* @param TYPE - type of the component.
* @param NAME - name of the variable.
* @param QUALIFIER_NAME - qualifier name is needed if there are multiple components registered of the same type.
* If there is one component registered only then TYPE info is enought to search for component.
*/
#define OATPP_COMPONENT(TYPE, ...) \
OATPP_MACRO_EXPAND(OATPP_MACRO_MACRO_SELECTOR(OATPP_MACRO_COMPONENT_, (__VA_ARGS__)) (TYPE, __VA_ARGS__))
/**
* Create component that then can be injected in other application classes.
* @param TYPE - type of the component.
* @param NAME - name of the component field.
*/
#define OATPP_CREATE_COMPONENT(TYPE, NAME) \
oatpp::base::Environment::Component<TYPE> NAME = oatpp::base::Environment::Component<TYPE>
#endif /* oatpp_macro_component_hpp */
| vincent-in-black-sesame/oat | src/oatpp/core/macro/component.hpp | C++ | apache-2.0 | 3,198 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#include "Caret.hpp"
#include <cstdlib>
#include <algorithm>
namespace oatpp { namespace parser {
const char* const Caret::ERROR_INVALID_INTEGER = "ERROR_INVALID_INTEGER";
const char* const Caret::ERROR_INVALID_FLOAT = "ERROR_INVALID_FLOAT";
const char* const Caret::ERROR_INVALID_BOOLEAN = "ERROR_INVALID_BOOLEAN";
const char* const Caret::ERROR_NO_OPEN_TAG = "ERROR_NO_OPEN_TAG";
const char* const Caret::ERROR_NO_CLOSE_TAG = "ERROR_NO_CLOSE_TAG";
const char* const Caret::ERROR_NAME_EXPECTED = "ERROR_NAME_EXPECTED";
/////////////////////////////////////////////////////////////////////////////////
// Caret::Label
Caret::Label::Label(Caret* caret)
: m_caret(caret)
, m_start((caret != nullptr) ? caret->m_pos : -1)
, m_end(-1)
{}
void Caret::Label::start() {
m_start = m_caret->m_pos;
m_end = -1;
}
void Caret::Label::end() {
m_end = m_caret->m_pos;
}
const char* Caret::Label::getData(){
return &m_caret->m_data[m_start];
}
v_buff_size Caret::Label::getSize(){
if(m_end == -1) {
return m_caret->m_pos - m_start;
}
return m_end - m_start;
}
v_buff_size Caret::Label::getStartPosition() {
return m_start;
};
v_buff_size Caret::Label::getEndPosition() {
return m_end;
};
oatpp::String Caret::Label::toString(){
v_buff_size end = m_end;
if(end == -1){
end = m_caret->m_pos;
}
return oatpp::String((const char*)&m_caret->m_data[m_start], end - m_start);
}
std::string Caret::Label::std_str(){
v_buff_size end = m_end;
if(end == -1){
end = m_caret->m_pos;
}
return std::string((const char*) (&m_caret->m_data[m_start]), end - m_start);
}
Caret::Label::operator bool() const {
return m_caret != nullptr;
}
/////////////////////////////////////////////////////////////////////////////////
// Caret::StateSaveGuard
Caret::StateSaveGuard::StateSaveGuard(Caret& caret)
: m_caret(caret)
, m_savedPosition(caret.m_pos)
, m_savedErrorMessage(caret.m_errorMessage)
, m_savedErrorCode(caret.m_errorCode)
{}
Caret::StateSaveGuard::~StateSaveGuard() {
m_caret.m_pos = m_savedPosition;
m_caret.m_errorMessage = m_savedErrorMessage;
m_caret.m_errorCode = m_savedErrorCode;
}
v_buff_size Caret::StateSaveGuard::getSavedPosition() {
return m_savedPosition;
}
const char* Caret::StateSaveGuard::getSavedErrorMessage() {
return m_savedErrorMessage;
}
v_int64 Caret::StateSaveGuard::getSavedErrorCode() {
return m_savedErrorCode;
}
/////////////////////////////////////////////////////////////////////////////////
// Caret
Caret::Caret(const char* text)
: Caret(text, std::strlen(text))
{}
Caret::Caret(const char* parseData, v_buff_size dataSize)
: m_data(parseData)
, m_size(dataSize)
, m_pos(0)
, m_errorMessage(nullptr)
, m_errorCode(0)
{}
Caret::Caret(const oatpp::String& str)
: Caret(str->data(), str->size())
{
m_dataMemoryHandle = str.getPtr();
}
std::shared_ptr<Caret> Caret::createShared(const char* text){
return std::make_shared<Caret>(text);
}
std::shared_ptr<Caret> Caret::createShared(const char* parseData, v_buff_size dataSize){
return std::make_shared<Caret>(parseData, dataSize);
}
std::shared_ptr<Caret> Caret::createShared(const oatpp::String& str){
return std::make_shared<Caret>(str->data(), str->size());
}
Caret::~Caret(){
}
const char* Caret::getData(){
return m_data;
}
const char* Caret::getCurrData(){
return &m_data[m_pos];
}
v_buff_size Caret::getDataSize(){
return m_size;
}
std::shared_ptr<std::string> Caret::getDataMemoryHandle() {
return m_dataMemoryHandle;
}
void Caret::setPosition(v_buff_size position){
m_pos = position;
}
v_buff_size Caret::getPosition(){
return m_pos;
}
void Caret::setError(const char* errorMessage, v_int64 errorCode){
m_errorMessage = errorMessage;
m_errorCode = errorCode;
}
const char* Caret::getErrorMessage() {
return m_errorMessage;
}
v_int64 Caret::getErrorCode() {
return m_errorCode;
}
bool Caret::hasError() {
return m_errorMessage != nullptr;
}
void Caret::clearError() {
m_errorMessage = nullptr;
m_errorCode = 0;
}
Caret::Label Caret::putLabel() {
return Label(this);
}
void Caret::inc(){
m_pos ++;
}
void Caret::inc(v_buff_size amount){
m_pos+= amount;
}
bool Caret::skipBlankChars(){
while(m_pos < m_size){
v_char8 a = m_data[m_pos];
if(a != ' ' && a != '\t' && a != '\n' && a != '\r' && a != '\f')
return true;
m_pos ++;
}
return false;
}
bool Caret::skipChar(v_char8 c) {
while(m_pos < m_size){
if(m_data[m_pos] != c)
return true;
m_pos ++;
}
return false;
}
bool Caret::findChar(v_char8 c){
while(m_pos < m_size){
if(m_data[m_pos] == c)
return true;
m_pos ++;
}
return false;
}
bool Caret::skipCharsFromSet(const char* set){
return skipCharsFromSet(set, std::strlen(set));
}
bool Caret::skipCharsFromSet(const char* set, v_buff_size setSize){
while(m_pos < m_size){
if(!isAtCharFromSet(set, setSize)){
return true;
}
m_pos++;
}
return false;
}
v_buff_size Caret::findCharFromSet(const char* set){
return findCharFromSet(set, std::strlen(set));
}
v_buff_size Caret::findCharFromSet(const char* set, v_buff_size setSize){
while(m_pos < m_size){
v_char8 a = m_data[m_pos];
for(v_buff_size i = 0; i < setSize; i++){
if(set[i] == a)
return a;
}
m_pos ++;
}
return -1;
}
bool Caret::findRN() {
while(m_pos < m_size){
if(m_data[m_pos] == '\r'){
if(m_pos + 1 < m_size && m_data[m_pos + 1] == '\n'){
return true;
}
}
m_pos ++;
}
return false;
}
bool Caret::skipRN() {
if(m_pos + 1 < m_size && m_data[m_pos] == '\r' && m_data[m_pos + 1] == '\n'){
m_pos += 2;
return true;
}
return false;
}
bool Caret::isAtRN() {
return (m_pos + 1 < m_size && m_data[m_pos] == '\r' && m_data[m_pos + 1] == '\n');
}
bool Caret::findROrN() {
while(m_pos < m_size) {
v_char8 a = m_data[m_pos];
if(a == '\r' || a == '\n') {
return true;
}
m_pos ++;
}
return false;
}
bool Caret::skipRNOrN() {
if(m_pos < m_size - 1 && m_data[m_pos] == '\r' && m_data[m_pos + 1] == '\n') {
m_pos += 2;
return true;
}
if(m_pos < m_size && m_data[m_pos] == '\n') {
m_pos ++;
return true;
}
return false;
}
bool Caret::skipAllRsAndNs() {
bool skipped = false;
while(m_pos < m_size) {
v_char8 a = m_data[m_pos];
if(a == '\r' || a == '\n') {
m_pos ++;
skipped = true;
} else {
break;
}
}
return skipped;
}
v_int64 Caret::parseInt(int base) {
char* end;
char* start = (char*)&m_data[m_pos];
v_int64 result = (v_int64)std::strtoll(start, &end, base);
if(start == end){
m_errorMessage = ERROR_INVALID_INTEGER;
}
m_pos = ((v_buff_size) end - (v_buff_size) m_data);
return result;
}
v_uint64 Caret::parseUnsignedInt(int base) {
char* end;
char* start = (char*)&m_data[m_pos];
v_uint64 result = (v_uint64)std::strtoull(start, &end, base);
if(start == end){
m_errorMessage = ERROR_INVALID_INTEGER;
}
m_pos = ((v_buff_size) end - (v_buff_size) m_data);
return result;
}
v_float32 Caret::parseFloat32(){
char* end;
char* start = (char*)&m_data[m_pos];
v_float32 result = std::strtof(start , &end);
if(start == end){
m_errorMessage = ERROR_INVALID_FLOAT;
}
m_pos = ((v_buff_size) end - (v_buff_size) m_data);
return result;
}
v_float64 Caret::parseFloat64(){
char* end;
char* start = (char*)&m_data[m_pos];
v_float64 result = std::strtod(start , &end);
if(start == end){
m_errorMessage = ERROR_INVALID_FLOAT;
}
m_pos = ((v_buff_size) end - (v_buff_size) m_data);
return result;
}
bool Caret::isAtText(const char* text, bool skipIfTrue){
return isAtText(text, std::strlen(text), skipIfTrue);
}
bool Caret::isAtText(const char* text, v_buff_size textSize, bool skipIfTrue){
if(textSize <= m_size - m_pos){
for(v_buff_size i = 0; i < textSize; i++){
if(text[i] != m_data[m_pos + i]){
return false;
}
}
if(skipIfTrue) {
m_pos = m_pos + textSize;
}
return true;
}else{
return false;
}
}
bool Caret::isAtTextNCS(const char* text, bool skipIfTrue){
return isAtTextNCS(text, std::strlen(text), skipIfTrue);
}
bool Caret::isAtTextNCS(const char* text, v_buff_size textSize, bool skipIfTrue){
if(textSize <= m_size - m_pos){
for(v_buff_size i = 0; i < textSize; i++){
v_char8 c1 = text[i];
v_char8 c2 = m_data[m_pos + i];
if(c1 >= 'a' && c1 <= 'z'){
c1 = 'A' + c1 - 'a';
}
if(c2 >= 'a' && c2 <= 'z'){
c2 = 'A' + c2 - 'a';
}
if(c1 != c2){
return false;
}
}
if(skipIfTrue) {
m_pos = m_pos + textSize;
}
return true;
}else{
return false;
}
}
Caret::Label Caret::parseStringEnclosed(char openChar, char closeChar, char escapeChar){
if(canContinueAtChar(openChar, 1)){
auto label = putLabel();
while(canContinue()){
v_char8 a = m_data[m_pos];
if(a == escapeChar){
m_pos++;
} else if(a == closeChar){
label.end();
m_pos++;
return label;
}
m_pos++;
}
m_errorMessage = ERROR_NO_CLOSE_TAG;
}else{
m_errorMessage = ERROR_NO_OPEN_TAG;
}
return Label(nullptr);
}
bool Caret::findText(const char* text) {
return findText(text, std::strlen(text));
}
bool Caret::findText(const char* text, v_buff_size textSize) {
m_pos = (std::search(&m_data[m_pos], &m_data[m_size], text, text + textSize) - m_data);
return m_pos != m_size;
}
bool Caret::isAtCharFromSet(const char* set) const{
return isAtCharFromSet(set, std::strlen(set));
}
bool Caret::isAtCharFromSet(const char* set, v_buff_size setSize) const{
v_char8 a = m_data[m_pos];
for(v_buff_size i = 0; i < setSize; i++){
if(a == set[i]){
return true;
}
}
return false;
}
bool Caret::isAtChar(v_char8 c) const{
return m_data[m_pos] == c;
}
bool Caret::isAtBlankChar() const{
v_char8 a = m_data[m_pos];
return (a == ' ' || a == '\t' || a == '\n' || a == '\r' || a == '\b' || a == '\f');
}
bool Caret::isAtDigitChar() const{
v_char8 a = m_data[m_pos];
return (a >= '0' && a <= '9');
}
bool Caret::canContinueAtChar(v_char8 c) const{
return m_pos < m_size && m_errorMessage == nullptr && m_data[m_pos] == c;
}
bool Caret::canContinueAtChar(v_char8 c, v_buff_size skipChars){
if(m_pos < m_size && m_errorMessage == nullptr && m_data[m_pos] == c){
m_pos = m_pos + skipChars;
return true;
}
return false;
}
bool Caret::canContinue() const{
return m_pos < m_size && m_errorMessage == nullptr;
}
}}
| vincent-in-black-sesame/oat | src/oatpp/core/parser/Caret.cpp | C++ | apache-2.0 | 12,677 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef oatpp_parser_Caret_hpp
#define oatpp_parser_Caret_hpp
#include "oatpp/core/Types.hpp"
namespace oatpp { namespace parser {
/**
* Helper class to do parsing operations
*/
class Caret {
public:
static const char* const ERROR_INVALID_INTEGER;
static const char* const ERROR_INVALID_FLOAT;
static const char* const ERROR_INVALID_BOOLEAN;
static const char* const ERROR_NO_OPEN_TAG;
static const char* const ERROR_NO_CLOSE_TAG;
static const char* const ERROR_NAME_EXPECTED;
public:
/**
* Class to label parsing data.
*/
class Label {
private:
Caret* m_caret;
v_buff_size m_start;
v_buff_size m_end;
public:
/**
* Constructor.
* @param caret.
*/
Label(Caret* caret);
/**
* Set current caret position as a starting point for label.
*/
void start();
/**
* Fix current caret position as an end point for label.
*/
void end();
/**
* Get pointer to a labeled data.
* @return
*/
const char* getData();
/**
* Get size of labeled data.
* @return
*/
v_buff_size getSize();
/**
* Get start position of the label.
* @return
*/
v_buff_size getStartPosition();
/**
* Get end position of the label.
* @return - end position of the label or `-1` if end() wasn't called yet.
*/
v_buff_size getEndPosition();
/**
* Same as`toString(true).`
* @return - &id:oatpp::String;.
*/
oatpp::String toString();
/**
* Create `std::string` from labeled data.
* @return - `std::string`.
*/
std::string std_str();
explicit operator bool() const;
};
/**
* Caret state saver guard.
*/
class StateSaveGuard {
private:
Caret& m_caret;
v_buff_size m_savedPosition;
const char* m_savedErrorMessage;
v_int64 m_savedErrorCode;
public:
/**
* Constructor.
* @param caret.
*/
StateSaveGuard(Caret& caret);
/**
* Destructor. Restore saved state.
*/
~StateSaveGuard();
/**
* Get caret saved position.
* @return
*/
v_buff_size getSavedPosition();
/**
* Get caret saved error message.
* @return
*/
const char* getSavedErrorMessage();
/**
* Get caret saved error code.
* @return
*/
v_int64 getSavedErrorCode();
};
private:
const char* m_data;
v_buff_size m_size;
v_buff_size m_pos;
const char* m_errorMessage;
v_int64 m_errorCode;
std::shared_ptr<std::string> m_dataMemoryHandle;
public:
Caret(const char* text);
Caret(const char* parseData, v_buff_size dataSize);
Caret(const oatpp::String& str);
public:
static std::shared_ptr<Caret> createShared(const char* text);
static std::shared_ptr<Caret> createShared(const char* parseData, v_buff_size dataSize);
static std::shared_ptr<Caret> createShared(const oatpp::String& str);
virtual ~Caret();
/**
* Get pointer to a data, passed to Caret constructor
* @return
*/
const char* getData();
/**
* Same as &getData()[position]
* @return
*/
const char* getCurrData();
/**
* Get size of a data
* @return
*/
v_buff_size getDataSize();
/**
* Get data memoryHandle.
* @return
*/
std::shared_ptr<std::string> getDataMemoryHandle();
/**
* Set caret position relative to data
* @param position
*/
void setPosition(v_buff_size position);
/**
* Get caret position relative to data
* @return
*/
v_buff_size getPosition();
/**
* Set error message and error code.
* Note that once error message is set, methods canContinue... will return false
* @param errorMessage
* @param errorCode
*/
void setError(const char* errorMessage, v_int64 errorCode = 0);
/**
* Get error message
* @return error message
*/
const char* getErrorMessage();
/**
* Get error code
* @return error code
*/
v_int64 getErrorCode();
/**
* Check if error is set for the Caret
* @return
*/
bool hasError();
/**
* Clear error message and error code
*/
void clearError();
/**
* Create Label(this);
* @return Label
*/
Label putLabel();
/**
* Increase caret position by one
*/
void inc();
/**
* Increase caret position by amount
* @param amount
*/
void inc(v_buff_size amount);
/**
* Skip chars: [' ', '\t', '\n', '\r','\f']
* @return true if other char found
*/
bool skipBlankChars();
/**
* Skip char
* @param c
* @return true if other char found
*/
bool skipChar(v_char8 c);
/**
* Find char. Position will be set to a found char. If
* no such char found - position will be set to a dataSize;
* @param c
* @return true if found
*/
bool findChar(v_char8 c);
/**
* Skip chars defined by set.
* ex. skipCharsFromSet("abc") - will skip all 'a', 'b', 'c' chars
* @param set
* @return true if other char found
*/
bool skipCharsFromSet(const char* set);
/**
* Skip chars defined by set.
* ex. skipCharsFromSet("abc", 3) - will skip all 'a', 'b', 'c' chars
* @param set
* @param setSize
* @return true if other char found
*/
bool skipCharsFromSet(const char* set, v_buff_size setSize);
/**
* Find one of chars defined by set.
* @param set
* @return char found or -1 if no char found
*/
v_buff_size findCharFromSet(const char* set);
/**
* Find one of chars defined by set.
* @param set
* @param setSize
* @return char found or -1 if no char found
*/
v_buff_size findCharFromSet(const char* set, v_buff_size setSize);
/**
* Find "\r\n" chars
* @return true if found
*/
bool findRN();
/**
* Skip "\r\n"
* @return True if position changes. False if caret not at "\r\n"
*/
bool skipRN();
/**
* Check if caret at "\r\n" chars
* @return
*/
bool isAtRN();
/**
* Find '\r' char of '\n' char
* @return true if found '\r' or '\n'
*/
bool findROrN();
/**
* if at "\r\n" - skip.
* if at "\n" - skip.
* @return true if position changed
*/
bool skipRNOrN();
/**
* skip any sequence of '\r' and '\n'
* @return true if position changed
*/
bool skipAllRsAndNs();
/**
* parse integer value starting from the current position.
* Using function std::strtol()
*
* Warning: position may go out of @Caret::getSize() bound.
*
* @param base - base is passed to std::strtol function
* @return parsed value
*/
v_int64 parseInt(int base = 10);
/**
* parse integer value starting from the current position.
* Using function std::strtoul()
*
* Warning: position may go out of @Caret::getSize() bound.
*
* @param base - base is passed to std::strtoul function
* @return parsed value
*/
v_uint64 parseUnsignedInt(int base = 10);
/**
* parse float value starting from the current position.
* Using function std::strtof()
*
* Warning: position may go out of @Caret::getSize() bound.
*
* @return parsed value
*/
v_float32 parseFloat32();
/**
* parse float value starting from the current position.
* Using function std::strtod()
*
* Warning: position may go out of @Caret::getSize() bound.
*
* @return parsed value
*/
v_float64 parseFloat64();
/**
* Check if follows text
* @param text
* @param skipIfTrue - increase position if true
* @return
*/
bool isAtText(const char* text, bool skipIfTrue = false);
/**
* Check if follows text
* @param text
* @param textSize
* @param skipIfTrue - increase position if true
* @return
*/
bool isAtText(const char* text, v_buff_size textSize, bool skipIfTrue = false);
/**
* Check if follows text (Not Case Sensitive)
* @param text
* @param skipIfTrue - increase position if true
* @return
*/
bool isAtTextNCS(const char* text, bool skipIfTrue = false);
/**
* Check if follows text (Not Case Sensitive)
* @param text
* @param textSize
* @param skipIfTrue - increase position if true
* @return
*/
bool isAtTextNCS(const char* text, v_buff_size textSize, bool skipIfTrue = false);
/**
* Parse enclosed string.
* ex. for data "'let\'s go'" parseStringEnclosed('\'', '\'', '\\')
* will return Label to "let\'s go" without enclosing '\'' chars
* @param openChar
* @param closeChar
* @param escapeChar
* @return
*/
Label parseStringEnclosed(char openChar, char closeChar, char escapeChar);
/**
* Find text and set position to found text
* @param text
* @return true if found
*/
bool findText(const char* text);
/**
* Find text and set position to found text
* @param text
* @param textSize
* @return true if found
*/
bool findText(const char* text, v_buff_size textSize);
/**
* Check if caret is at char defined by set
* ex. isAtCharFromSet("abc") - will return true for 'a', 'b', 'c' chars
* @param set
* @return
*/
bool isAtCharFromSet(const char* set) const;
/**
* Check if caret is at char defined by set
* ex. isAtCharFromSet("abc", 3) - will return true for 'a', 'b', 'c' chars
* @param set
* @param setSize
* @return
*/
bool isAtCharFromSet(const char* set, v_buff_size setSize) const;
/**
* Check if caret is at char
* @param c
* @return
*/
bool isAtChar(v_char8 c) const;
/**
* Check if caret is at one of chars [' ', '\t', '\n', '\r','\f']
* @return
*/
bool isAtBlankChar() const;
/**
* Check if caret is at digit
* @return
*/
bool isAtDigitChar() const;
/**
* Check if caret is at char, and no error is set
* @param c
* @return
*/
bool canContinueAtChar(v_char8 c) const;
/**
* Check if caret is at char, and no error is set.
* If true inc position by skipChars
* @param c
* @param skipChars
* @return
*/
bool canContinueAtChar(v_char8 c, v_buff_size skipChars);
/**
* Check if caret position < dataSize and not error is set
* @return
*/
bool canContinue() const;
};
}}
#endif /* oatpp_parser_Caret_hpp */
| vincent-in-black-sesame/oat | src/oatpp/core/parser/Caret.hpp | C++ | apache-2.0 | 11,120 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#include "ParsingError.hpp"
namespace oatpp { namespace parser {
ParsingError::ParsingError(const oatpp::String &message, v_int64 code, v_buff_size position)
:std::runtime_error(*message)
, m_message(message)
, m_code(code)
, m_position(position)
{}
oatpp::String ParsingError::getMessage() const {
return m_message;
}
v_int64 ParsingError::getCode() const {
return m_code;
}
v_buff_size ParsingError::getPosition() const {
return m_position;
}
}} | vincent-in-black-sesame/oat | src/oatpp/core/parser/ParsingError.cpp | C++ | apache-2.0 | 1,463 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef oatpp_parser_ParsingError_hpp
#define oatpp_parser_ParsingError_hpp
#include "oatpp/core/Types.hpp"
namespace oatpp { namespace parser {
/**
* Thrown when parsing error occurred and ParsingCaret object is not accessible for user.
* If parsing was made via oatpp::parser::ParsingCaret and ParsingCaret is accessible for user
* then do not throw this error.- User should read error from ParsingCaret::getError()
*/
class ParsingError : public std::runtime_error {
private:
oatpp::String m_message;
v_int64 m_code;
v_buff_size m_position;
public:
/**
* Constructor
* @param message
* @param position
*/
ParsingError(const oatpp::String &message, v_int64 code, v_buff_size position);
/**
* get error message
* @return
*/
oatpp::String getMessage() const;
/**
* get error code
* @return
*/
v_int64 getCode() const;
/**
* get parsing position of the error
* @return
*/
v_buff_size getPosition() const;
};
}}
#endif //oatpp_parser_ParsingError_hpp
| vincent-in-black-sesame/oat | src/oatpp/core/parser/ParsingError.hpp | C++ | apache-2.0 | 2,020 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef oatpp_provider_Invalidator_hpp
#define oatpp_provider_Invalidator_hpp
#include "oatpp/core/base/Countable.hpp"
#include <memory>
namespace oatpp { namespace provider {
/**
* Abstract resource invalidator.
* @tparam T - resource class.
*/
template<class T>
class Invalidator : public oatpp::base::Countable {
public:
/**
* Default virtual destructor.
*/
virtual ~Invalidator() = default;
/**
* Invalidate resource that was previously created by the correspondent provider. <br>
* Use-case: if provider is pool based - you can signal that this resource should not be reused anymore.
* @param resource
*/
virtual void invalidate(const std::shared_ptr<T> &resource) = 0;
};
}}
#endif //oatpp_provider_Invalidator_hpp
| vincent-in-black-sesame/oat | src/oatpp/core/provider/Invalidator.hpp | C++ | apache-2.0 | 1,754 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>,
* Matthias Haselmaier <mhaselmaier@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef oatpp_provider_Pool_hpp
#define oatpp_provider_Pool_hpp
#include "Provider.hpp"
#include "oatpp/core/async/CoroutineWaitList.hpp"
#include <thread>
#include <condition_variable>
namespace oatpp { namespace provider {
template<class TResource, class AcquisitionProxyImpl>
class PoolTemplate; // FWD
/**
* Pool acquisition proxy template.
* @tparam TResource - abstract resource interface type, Ex.: `IOStream`.
* @tparam AcquisitionProxyImpl - implementation of proxy.
*/
template<class TResource, class AcquisitionProxyImpl>
class AcquisitionProxy : public TResource {
friend PoolTemplate<TResource, AcquisitionProxyImpl>;
public:
/**
* Convenience typedef for Pool.
*/
typedef PoolTemplate<TResource, AcquisitionProxyImpl> PoolInstance;
private:
void __pool__invalidate() {
m_valid = false;
}
provider::ResourceHandle<TResource> __pool__getUnderlyingResource() {
return _handle;
}
protected:
provider::ResourceHandle<TResource> _handle;
private:
std::shared_ptr<PoolInstance> m_pool;
bool m_valid;
public:
/**
* Constructor.
* @param resource - base resource.
* @param pool - &l:AcquisitionProxy::PoolInstance;.
*/
AcquisitionProxy(const provider::ResourceHandle<TResource>& resource, const std::shared_ptr<PoolInstance>& pool)
: _handle(resource)
, m_pool(pool)
, m_valid(true)
{}
/**
* Virtual destructor.
*/
virtual ~AcquisitionProxy() {
m_pool->release(std::move(_handle), m_valid);
}
};
template<class TResource, class AcquisitionProxyImpl>
class PoolTemplate : public oatpp::base::Countable, public async::CoroutineWaitList::Listener {
friend AcquisitionProxy<TResource, AcquisitionProxyImpl>;
private:
struct PoolRecord {
provider::ResourceHandle<TResource> resource;
v_int64 timestamp;
};
private:
class ResourceInvalidator : public provider::Invalidator<TResource> {
public:
void invalidate(const std::shared_ptr<TResource>& resource) override {
auto proxy = std::static_pointer_cast<AcquisitionProxyImpl>(resource);
proxy->__pool__invalidate();
const auto& handle = proxy->__pool__getUnderlyingResource();
handle.invalidator->invalidate(handle.object);
}
};
private:
void onNewItem(async::CoroutineWaitList& list) override {
std::unique_lock<std::mutex> guard(m_lock);
if(!m_running) {
guard.unlock();
list.notifyAll();
return;
}
if(m_counter < m_maxResources || m_bench.size() > 0) {
guard.unlock();
list.notifyFirst();
}
}
void release(provider::ResourceHandle<TResource>&& resource, bool canReuse) {
{
std::lock_guard<std::mutex> guard(m_lock);
if(!m_running) {
-- m_counter;
return;
}
if(canReuse) {
m_bench.push_back({resource, oatpp::base::Environment::getMicroTickCount()});
} else {
-- m_counter;
}
}
m_condition.notify_one();
m_waitList.notifyFirst();
}
private:
static void cleanupTask(std::shared_ptr<PoolTemplate> pool) {
while(pool->m_running) { // timer-based cleanup loop
{
std::lock_guard<std::mutex> guard(pool->m_lock);
auto ticks = oatpp::base::Environment::getMicroTickCount();
auto i = pool->m_bench.begin();
while (i != pool->m_bench.end()) {
auto elapsed = ticks - i->timestamp;
if(elapsed > pool->m_maxResourceTTL) {
i->resource.invalidator->invalidate(i->resource.object);
i = pool->m_bench.erase(i);
pool->m_counter --;
} else {
i ++;
}
}
}
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
{ /* invalidate all pooled resources */
std::lock_guard<std::mutex> guard(pool->m_lock);
auto i = pool->m_bench.begin();
while (i != pool->m_bench.end()) {
i->resource.invalidator->invalidate(i->resource.object);
i = pool->m_bench.erase(i);
pool->m_counter --;
}
pool->m_finished = true;
}
pool->m_condition.notify_all();
}
private:
std::shared_ptr<ResourceInvalidator> m_invalidator;
std::shared_ptr<Provider<TResource>> m_provider;
v_int64 m_counter{0};
v_int64 m_maxResources;
v_int64 m_maxResourceTTL;
std::atomic<bool> m_running{true};
bool m_finished{false};
private:
std::list<PoolRecord> m_bench;
async::CoroutineWaitList m_waitList;
std::condition_variable m_condition;
std::mutex m_lock;
std::chrono::duration<v_int64, std::micro> m_timeout;
protected:
PoolTemplate(const std::shared_ptr<Provider<TResource>>& provider, v_int64 maxResources, v_int64 maxResourceTTL, const std::chrono::duration<v_int64, std::micro>& timeout)
: m_invalidator(std::make_shared<ResourceInvalidator>())
, m_provider(provider)
, m_maxResources(maxResources)
, m_maxResourceTTL(maxResourceTTL)
, m_timeout(timeout)
{}
static void startCleanupTask(const std::shared_ptr<PoolTemplate>& _this) {
std::thread poolCleanupTask(cleanupTask, _this);
poolCleanupTask.detach();
}
static provider::ResourceHandle<TResource> get(const std::shared_ptr<PoolTemplate>& _this) {
auto readyPredicate = [&_this]() { return !_this->m_running || !_this->m_bench.empty() || _this->m_counter < _this->m_maxResources; };
std::unique_lock<std::mutex> guard{_this->m_lock};
if (_this->m_timeout == std::chrono::microseconds::zero())
{
while (!readyPredicate()) {
_this->m_condition.wait(guard);
}
} else if (!_this->m_condition.wait_for(guard, _this->m_timeout, std::move(readyPredicate))) {
return nullptr;
}
if(!_this->m_running) {
return nullptr;
}
if (_this->m_bench.size() > 0) {
auto record = _this->m_bench.front();
_this->m_bench.pop_front();
return provider::ResourceHandle<TResource>(
std::make_shared<AcquisitionProxyImpl>(record.resource, _this),
_this->m_invalidator
);
} else {
++ _this->m_counter;
}
guard.unlock();
try {
return provider::ResourceHandle<TResource>(
std::make_shared<AcquisitionProxyImpl>(_this->m_provider->get(), _this),
_this->m_invalidator
);
} catch (...) {
guard.lock();
--_this->m_counter;
return nullptr;
}
}
static async::CoroutineStarterForResult<const provider::ResourceHandle<TResource>&> getAsync(const std::shared_ptr<PoolTemplate>& _this) {
class GetCoroutine : public oatpp::async::CoroutineWithResult<GetCoroutine, const provider::ResourceHandle<TResource>&> {
private:
std::shared_ptr<PoolTemplate> m_pool;
std::chrono::steady_clock::time_point m_startTime{std::chrono::steady_clock::now()};
public:
GetCoroutine(const std::shared_ptr<PoolTemplate>& pool)
: m_pool(pool)
{}
bool timedout() const noexcept {
return m_pool->m_timeout != std::chrono::microseconds::zero() && m_pool->m_timeout < (std::chrono::steady_clock::now() - m_startTime);
}
async::Action act() override {
if (timedout()) return this->_return(nullptr);
{
/* Careful!!! Using non-async lock */
std::unique_lock<std::mutex> guard(m_pool->m_lock);
if (m_pool->m_running && m_pool->m_bench.size() == 0 && m_pool->m_counter >= m_pool->m_maxResources) {
guard.unlock();
return m_pool->m_timeout == std::chrono::microseconds::zero()
? async::Action::createWaitListAction(&m_pool->m_waitList)
: async::Action::createWaitListActionWithTimeout(&m_pool->m_waitList, m_startTime + m_pool->m_timeout);
}
if(!m_pool->m_running) {
guard.unlock();
return this->_return(nullptr);
}
if (m_pool->m_bench.size() > 0) {
auto record = m_pool->m_bench.front();
m_pool->m_bench.pop_front();
guard.unlock();
return this->_return(provider::ResourceHandle<TResource>(
std::make_shared<AcquisitionProxyImpl>(record.resource, m_pool),
m_pool->m_invalidator
));
} else {
++ m_pool->m_counter;
}
}
return m_pool->m_provider->getAsync().callbackTo(&GetCoroutine::onGet);
}
async::Action onGet(const provider::ResourceHandle<TResource>& resource) {
return this->_return(provider::ResourceHandle<TResource>(
std::make_shared<AcquisitionProxyImpl>(resource, m_pool),
m_pool->m_invalidator
));
}
async::Action handleError(oatpp::async::Error* error) override {
{
/* Careful!!! Using non-async lock */
std::lock_guard<std::mutex> guard(m_pool->m_lock);
-- m_pool->m_counter;
}
return error;
}
};
return GetCoroutine::startForResult(_this);
}
public:
static std::shared_ptr<PoolTemplate> createShared(const std::shared_ptr<Provider<TResource>>& provider,
v_int64 maxResources,
const std::chrono::duration<v_int64, std::micro>& maxResourceTTL)
{
/* "new" is called directly to keep constructor private */
auto ptr = std::shared_ptr<PoolTemplate>(new PoolTemplate(provider, maxResources, maxResourceTTL.count()));
startCleanupTask(ptr);
return ptr;
}
virtual ~PoolTemplate() {
stop();
}
void stop() {
{
std::lock_guard<std::mutex> guard(m_lock);
if (!m_running) {
return;
}
m_running = false;
m_counter -= m_bench.size();
m_bench.clear();
}
m_condition.notify_all();
m_waitList.notifyAll();
{
std::unique_lock<std::mutex> guard(m_lock);
while (!m_finished) {
m_condition.wait(guard);
}
}
m_provider->stop();
}
v_int64 getCounter() {
std::lock_guard<std::mutex> guard(m_lock);
return m_counter;
}
};
/**
* Pool template class.
* @tparam TProvider - base class for pool to inherit, ex.: ServerConnectionProvider.
* @tparam TResource - abstract resource interface type, Ex.: `IOStream`. Must be the same as a return-type of Provider.
* @tparam AcquisitionProxyImpl - implementation of &l:AcquisitionProxy;.
*/
template<class TProvider, class TResource, class AcquisitionProxyImpl>
class Pool :
public TProvider,
public std::enable_shared_from_this<Pool<TProvider, TResource, AcquisitionProxyImpl>>,
public PoolTemplate<TResource, AcquisitionProxyImpl> {
private:
typedef PoolTemplate<TResource, AcquisitionProxyImpl> TPool;
protected:
/*
* Protected Constructor.
* @param provider
* @param maxResources
* @param maxResourceTTL
* @param timeout
*/
Pool(const std::shared_ptr<TProvider>& provider,
v_int64 maxResources,
v_int64 maxResourceTTL,
const std::chrono::duration<v_int64, std::micro>& timeout = std::chrono::microseconds::zero()
)
: PoolTemplate<TResource, AcquisitionProxyImpl>(provider, maxResources, maxResourceTTL, timeout)
{
TProvider::m_properties = provider->getProperties();
}
public:
/**
* Create shared Pool.
* @param provider - resource provider.
* @param maxResources - max resource count in the pool.
* @param maxResourceTTL - max time-to-live for unused resource in the pool.
* @param timeout - optional timeout on &l:Pool::get (); and &l:Pool::getAsync (); operations.
* @return - `std::shared_ptr` of `Pool`.
*/
static std::shared_ptr<Pool> createShared(const std::shared_ptr<TProvider>& provider,
v_int64 maxResources,
const std::chrono::duration<v_int64, std::micro>& maxResourceTTL,
const std::chrono::duration<v_int64, std::micro>& timeout = std::chrono::microseconds::zero())
{
/* "new" is called directly to keep constructor private */
auto ptr = std::shared_ptr<Pool>(new Pool(provider, maxResources, maxResourceTTL.count(), timeout));
ptr->startCleanupTask(ptr);
return ptr;
}
/**
* Get resource.
* @return
*/
provider::ResourceHandle<TResource> get() override {
return TPool::get(this->shared_from_this());
}
/**
* Get resource asynchronously.
* @return
*/
async::CoroutineStarterForResult<const provider::ResourceHandle<TResource>&> getAsync() override {
return TPool::getAsync(this->shared_from_this());
}
/**
* Stop pool. <br>
* *Note: call to stop() may block.*
*/
void stop() override {
TPool::stop();
}
/**
* Get pool resource count. Both acquired and available.
* @return
*/
v_int64 getCounter() {
return TPool::getCounter();
}
};
}}
#endif // oatpp_provider_Pool_hpp
| vincent-in-black-sesame/oat | src/oatpp/core/provider/Pool.hpp | C++ | apache-2.0 | 13,969 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef oatpp_provider_Provider_hpp
#define oatpp_provider_Provider_hpp
#include "Invalidator.hpp"
#include "oatpp/core/async/Coroutine.hpp"
#include "oatpp/core/data/share/MemoryLabel.hpp"
namespace oatpp { namespace provider {
/**
* Resource handle template.
* @tparam T
*/
template<class T, class PTR>
struct ResourceHandleTemplate {
/**
* Default constructor.
*/
ResourceHandleTemplate() = default;
/**
* Nullptr constructor.
*/
ResourceHandleTemplate(std::nullptr_t) {}
/**
* Constructor.
* @param resourceObject
* @param resourceInvalidator
*/
ResourceHandleTemplate(const PTR& resourceObject,
const std::shared_ptr<Invalidator<T>> &resourceInvalidator)
: object(resourceObject), invalidator(resourceInvalidator)
{}
/**
* Pointer to the resource.
*/
PTR object;
/**
* Invalidator that can be used to invalidate the resource.
*/
std::shared_ptr<Invalidator<T>> invalidator;
inline bool operator == (std::nullptr_t) const {
return object.get() == nullptr;
}
inline bool operator != (std::nullptr_t) const {
return object.get() != nullptr;
}
explicit inline operator bool() const {
return object.operator bool();
}
/**
* Invalidates the resource so it can be disposed and cannot be reused anymore.
*/
virtual void invalidate() {
invalidator->invalidate(object);
}
};
/**
* Resource handle.
* @tparam T
*/
template<class T>
struct ResourceHandle : public ResourceHandleTemplate<T, std::shared_ptr<T>> {
/**
* Default constructor.
*/
ResourceHandle() = default;
/**
* Nullptr constructor.
*/
ResourceHandle(std::nullptr_t) {}
/**
* Constructor.
* @param resourceObject
* @param resourceInvalidator
*/
ResourceHandle(const std::shared_ptr<T>& resourceObject,
const std::shared_ptr<Invalidator<T>>& resourceInvalidator)
: ResourceHandleTemplate<T, std::shared_ptr<T>>(resourceObject, resourceInvalidator)
{}
};
/**
* Weak Resource handle.
* @tparam T
*/
template<class T>
struct WeakResourceHandle : public ResourceHandleTemplate<T, std::weak_ptr<T>> {
/**
* Default constructor.
*/
WeakResourceHandle() = default;
/**
* Nullptr constructor.
*/
WeakResourceHandle(std::nullptr_t) {}
/**
* Constructor.
* @param resourceObject
* @param resourceInvalidator
*/
WeakResourceHandle(const std::weak_ptr<T>& resourceObject,
const std::shared_ptr<Invalidator<T>>& resourceInvalidator)
: ResourceHandleTemplate<T, std::weak_ptr<T>>(resourceObject, resourceInvalidator)
{}
};
/**
* Abstract resource provider.
* @tparam T - resource class.
*/
template <class T>
class Provider : public oatpp::base::Countable {
protected:
void setProperty(const oatpp::String& key, const oatpp::String& value) {
m_properties[key] = value;
}
protected:
std::unordered_map<data::share::StringKeyLabelCI, data::share::StringKeyLabel> m_properties;
public:
/**
* Default constructor.
*/
Provider() = default;
/**
* Constructor.
* @param properties
*/
Provider(const std::unordered_map<data::share::StringKeyLabelCI, data::share::StringKeyLabel>& properties)
: m_properties(properties)
{}
/**
* Virtual destructor.
*/
virtual ~Provider() = default;
/**
* Some optional properties that user might want to know. <br>
* Note: All properties are optional and user should not rely on this.
*/
const std::unordered_map<data::share::StringKeyLabelCI, data::share::StringKeyLabel>& getProperties() const {
return m_properties;
}
/**
* Get optional property
*/
data::share::StringKeyLabel getProperty(const oatpp::String& key) const {
auto it = m_properties.find(key);
if(it == m_properties.end()) {
return nullptr;
}
return it->second;
}
/**
* Get resource.
* @return - resource.
*/
virtual ResourceHandle<T> get() = 0;
/**
* Get resource in Async manner.
* @return - &id:oatpp::async::CoroutineStarterForResult; of `T`.
*/
virtual async::CoroutineStarterForResult<const ResourceHandle<T>&> getAsync() = 0;
/**
* Stop provider and free associated resources.
*/
virtual void stop() = 0;
};
}}
#endif // oatpp_provider_Provider_hpp
| vincent-in-black-sesame/oat | src/oatpp/core/provider/Provider.hpp | C++ | apache-2.0 | 5,322 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#include "Binary.hpp"
namespace oatpp { namespace utils {
v_int64 Binary::nextP2(v_int64 v) {
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v |= v >> 32;
v++;
return v;
}
}} | vincent-in-black-sesame/oat | src/oatpp/core/utils/Binary.cpp | C++ | apache-2.0 | 1,215 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef oatpp_utils_Binary_hpp
#define oatpp_utils_Binary_hpp
#include "oatpp/core/base/Environment.hpp"
namespace oatpp { namespace utils {
/**
* Collection of methods for binary operations and arithmetics.
*/
class Binary {
public:
/**
* Calculate the next power of 2. <br>
* Example: <br>
* `nextP2(127) = 128`, `nextP2(1025) = 2048`.
* @return
*/
static v_int64 nextP2(v_int64 v);
};
}}
#endif // oatpp_utils_Binary_hpp
| vincent-in-black-sesame/oat | src/oatpp/core/utils/Binary.hpp | C++ | apache-2.0 | 1,448 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#include "ConversionUtils.hpp"
#include <cstdlib>
namespace oatpp { namespace utils { namespace conversion {
v_int32 strToInt32(const char* str){
char* end;
return (v_int32) std::strtol(str, &end, 10);
}
v_int32 strToInt32(const oatpp::String& str, bool& success){
char* end;
v_int32 result = (v_int32) std::strtol(str->data(), &end, 10);
success = (((v_buff_size)end - (v_buff_size)str->data()) == str->size());
return result;
}
v_uint32 strToUInt32(const char* str){
char* end;
return (v_uint32) std::strtoul(str, &end, 10);
}
v_uint32 strToUInt32(const oatpp::String& str, bool& success){
char* end;
v_uint32 result = (v_uint32) std::strtoul(str->data(), &end, 10);
success = (((v_buff_size)end - (v_buff_size)str->data()) == str->size());
return result;
}
v_int64 strToInt64(const char* str){
char* end;
return std::strtoll(str, &end, 10);
}
v_int64 strToInt64(const oatpp::String& str, bool& success){
char* end;
v_int64 result = std::strtoll(str->data(), &end, 10);
success = (((v_buff_size)end - (v_buff_size)str->data()) == str->size());
return result;
}
v_uint64 strToUInt64(const char* str){
char* end;
return std::strtoull(str, &end, 10);
}
v_uint64 strToUInt64(const oatpp::String& str, bool& success){
char* end;
v_uint64 result = std::strtoull(str->data(), &end, 10);
success = (((v_buff_size)end - (v_buff_size)str->data()) == str->size());
return result;
}
v_buff_size int32ToCharSequence(v_int32 value, p_char8 data, v_buff_size n) {
return snprintf((char*)data, n, "%ld", (long) value);
}
v_buff_size uint32ToCharSequence(v_uint32 value, p_char8 data, v_buff_size n) {
return snprintf((char*)data, n, "%lu", (unsigned long) value);
}
v_buff_size int64ToCharSequence(v_int64 value, p_char8 data, v_buff_size n) {
return snprintf((char*)data, n, "%lld", (long long int) value);
}
v_buff_size uint64ToCharSequence(v_uint64 value, p_char8 data, v_buff_size n) {
return snprintf((char*)data, n, "%llu", (long long unsigned int) value);
}
oatpp::String int32ToStr(v_int32 value){
v_char8 buff [16]; // Max 10 digits with 1 sign. 16 is plenty enough.
auto size = int32ToCharSequence(value, &buff[0], 16);
if(size > 0){
return oatpp::String((const char*)&buff[0], size);
}
return nullptr;
}
oatpp::String uint32ToStr(v_uint32 value){
v_char8 buff [16]; // Max 10 digits. 16 is plenty enough.
auto size = uint32ToCharSequence(value, &buff[0], 16);
if(size > 0){
return oatpp::String((const char*)&buff[0], size);
}
return nullptr;
}
oatpp::String int64ToStr(v_int64 value){
v_char8 buff [32]; // Max 20 digits unsigned, 19 digits +1 sign signed.
auto size = int64ToCharSequence(value, &buff[0], 32);
if(size > 0){
return oatpp::String((const char*)&buff[0], size);
}
return nullptr;
}
oatpp::String uint64ToStr(v_uint64 value){
v_char8 buff [32]; // Max 20 digits.
auto size = uint64ToCharSequence(value, &buff[0], 32);
if(size > 0){
return oatpp::String((const char*)&buff[0], size);
}
return nullptr;
}
std::string int32ToStdStr(v_int32 value){
v_char8 buff [16];
auto size = int32ToCharSequence(value, &buff[0], 16);
if(size > 0){
return std::string((const char*)buff, size);
}
return nullptr;
}
std::string uint32ToStdStr(v_uint32 value){
v_char8 buff [16];
auto size = uint32ToCharSequence(value, &buff[0], 16);
if(size > 0){
return std::string((const char*)buff, size);
}
return nullptr;
}
std::string int64ToStdStr(v_int64 value){
v_char8 buff [32];
v_int32 size = v_int32(int64ToCharSequence(value, &buff[0], 32));
if(size > 0){
return std::string((const char*)buff, size);
}
return nullptr;
}
std::string uint64ToStdStr(v_uint64 value){
v_char8 buff [32];
auto size = uint64ToCharSequence(value, &buff[0], 32);
if(size > 0){
return std::string((const char*)buff, size);
}
return nullptr;
}
v_float32 strToFloat32(const char* str){
char* end;
return std::strtof(str, &end);
}
v_float32 strToFloat32(const oatpp::String& str, bool& success) {
char* end;
v_float32 result = std::strtof(str->data(), &end);
success = (((v_buff_size)end - (v_buff_size)str->data()) == str->size());
return result;
}
v_float64 strToFloat64(const char* str){
char* end;
return std::strtod(str, &end);
}
v_float64 strToFloat64(const oatpp::String& str, bool& success) {
char* end;
v_float64 result = std::strtod(str->data(), &end);
success = (((v_buff_size)end - (v_buff_size)str->data()) == str->size());
return result;
}
v_buff_size float32ToCharSequence(v_float32 value, p_char8 data, v_buff_size n, const char* format) {
return snprintf((char*)data, n, format, value);
}
v_buff_size float64ToCharSequence(v_float64 value, p_char8 data, v_buff_size n, const char* format) {
return snprintf((char*)data, n, format, value);
}
oatpp::String float32ToStr(v_float32 value, const char* format) {
v_char8 buff [100];
auto size = float32ToCharSequence(value, &buff[0], 100, format);
if(size > 0){
return oatpp::String((const char*)&buff[0], size);
}
return nullptr;
}
oatpp::String float64ToStr(v_float64 value, const char* format) {
v_char8 buff [100];
auto size = float64ToCharSequence(value, &buff[0], 100, format);
if(size > 0){
return oatpp::String((const char*)&buff[0], size);
}
return nullptr;
}
oatpp::String boolToStr(bool value) {
if(value){
return oatpp::String("true", 4);
} else {
return oatpp::String("false", 5);
}
}
bool strToBool(const oatpp::String& str, bool& success) {
if(str == "true"){
success = true;
return true;
} else if(str == "false"){
success = true;
return false;
}
success = false;
return false;
}
}}}
| vincent-in-black-sesame/oat | src/oatpp/core/utils/ConversionUtils.cpp | C++ | apache-2.0 | 7,098 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef oatpp_utils_ConversionUtils_hpp
#define oatpp_utils_ConversionUtils_hpp
#include "oatpp/core/data/mapping/type/Primitive.hpp"
#include "oatpp/core/Types.hpp"
#include "oatpp/core/base/Countable.hpp"
#include "oatpp/core/base/Environment.hpp"
#include <string>
namespace oatpp { namespace utils { namespace conversion {
/**
* String to 32-bit integer.
* @param str - string as `const char*`.
* @return - 32-bit integer value.
*/
v_int32 strToInt32(const char* str);
/**
* String to 32-bit integer.
* @param str - string as `oatpp::String`.
* @param success - out parameter. `true` if operation was successful. `false` otherwise.
* @return - 32-bit integer value.
*/
v_int32 strToInt32(const oatpp::String& str, bool& success);
/**
* String to 32-bit unsigned integer.
* @param str - string as `const char*`.
* @return - 32-bit unsigned integer value.
*/
v_uint32 strToUInt32(const char* str);
/**
* String to 32-bit unsigned integer.
* @param str - string as `oatpp::String`.
* @param success - out parameter. `true` if operation was successful. `false` otherwise.
* @return - 32-bit unsigned integer value.
*/
v_uint32 strToUInt32(const oatpp::String& str, bool& success);
/**
* String to 64-bit integer.
* @param str - string as `const char*`.
* @return - 64-bit integer value.
*/
v_int64 strToInt64(const char* str);
/**
* String to 64-bit integer.
* @param str - string as `oatpp::String`.
* @param success - out parameter. `true` if operation was successful. `false` otherwise.
* @return - 64-bit integer value.
*/
v_int64 strToInt64(const oatpp::String& str, bool& success);
/**
* String to 64-bit unsigned integer.
* @param str - string as `const char*`.
* @return - 64-bit unsigned integer value.
*/
v_uint64 strToUInt64(const char* str);
/**
* String to 64-bit unsigned integer.
* @param str - string as `oatpp::String`.
* @param success - out parameter. `true` if operation was successful. `false` otherwise.
* @return - 64-bit unsigned integer value.
*/
v_uint64 strToUInt64(const oatpp::String& str, bool& success);
/**
* Convert 32-bit integer to it's string representation.
* @param value - 32-bit integer value.
* @param data - buffer to write data to.
* @param n - buffer size.
* @return - length of the resultant string.
*/
v_buff_size int32ToCharSequence(v_int32 value, p_char8 data, v_buff_size n);
/**
* Convert 32-bit unsigned integer to it's string representation.
* @param value - 32-bit unsigned integer value.
* @param data - buffer to write data to.
* @param n - buffer size.
* @return - length of the resultant string.
*/
v_buff_size uint32ToCharSequence(v_uint32 value, p_char8 data, v_buff_size n);
/**
* Convert 64-bit integer to it's string representation.
* @param value - 64-bit integer value.
* @param data - buffer to write data to.
* @param n - buffer size.
* @return - length of the resultant string.
*/
v_buff_size int64ToCharSequence(v_int64 value, p_char8 data, v_buff_size n);
/**
* Convert 64-bit unsigned integer to it's string representation.
* @param value - 64-bit unsigned integer value.
* @param data - buffer to write data to.
* @param n - buffer size.
* @return - length of the resultant string.
*/
v_buff_size uint64ToCharSequence(v_uint64 value, p_char8 data, v_buff_size n);
/**
* Convert 32-bit integer to it's string representation.
* @param value - 32-bit integer value.
* @return - value as `oatpp::String`
*/
oatpp::String int32ToStr(v_int32 value);
/**
* Convert 32-bit unsigned integer to it's string representation.
* @param value - 32-bit unsigned integer value.
* @return - value as `oatpp::String`
*/
oatpp::String uint32ToStr(v_uint32 value);
/**
* Convert 64-bit integer to it's string representation.
* @param value - 64-bit integer value.
* @return - value as `oatpp::String`
*/
oatpp::String int64ToStr(v_int64 value);
/**
* Convert 64-bit unsigned integer to it's string representation.
* @param value - 64-bit unsigned integer value.
* @return - value as `oatpp::String`
*/
oatpp::String uint64ToStr(v_uint64 value);
/**
* Convert 32-bit integer to it's string representation.
* @param value - 32-bit integer value.
* @return - value as `std::string`
*/
std::string int32ToStdStr(v_int32 value);
/**
* Convert 32-bit unsigned integer to it's string representation.
* @param value - 32-bit unsigned integer value.
* @return - value as `std::string`
*/
std::string uint32ToStdStr(v_uint32 value);
/**
* Convert 64-bit integer to it's string representation.
* @param value - 64-bit integer value.
* @return - value as `std::string`
*/
std::string int64ToStdStr(v_int64 value);
/**
* Convert 64-bit unsigned integer to it's string representation.
* @param value - 64-bit unsigned integer value.
* @return - value as `std::string`
*/
std::string uint64ToStdStr(v_uint64 value);
/**
* Write value of primitive type (int, float, etc.) as it's string representation with pattern.
* @tparam T - primitive value type (int, float, etc.).
* @param value - actual value.
* @param data - buffer to write data to.
* @param n - buffer size.
* @param pattern - pattern as for `snprintf`.
* @return - length of the resultant string.
*/
template<typename T>
v_buff_size primitiveToCharSequence(T value, p_char8 data, v_buff_size n, const char *pattern) {
return snprintf((char*)data, n, pattern, value);
}
/**
* Write value of primitive type (int, float, etc.) as it's string representation with pattern.
* @tparam T - primitive value type (int, float, etc.).
* @param value - actual value.
* @param pattern - pattern as for `sprintf`.
* @return - length of the resultant string.
*/
template<typename T>
oatpp::String primitiveToStr(T value, const char* pattern){
v_char8 buff [100];
auto size = primitiveToCharSequence(value, &buff[0], 100, pattern);
if(size > 0){
return oatpp::String((const char*)&buff[0], size);
}
return nullptr;
}
/**
* String to 32-bit float.
* @param str - string as `const char*`.
* @return - 32-bit float value.
*/
v_float32 strToFloat32(const char* str);
/**
* String to 32-bit float.
* @param str - string as `oatpp::String`.
* @param success - out parameter. `true` if operation was successful. `false` otherwise.
* @return - 32-bit float value.
*/
v_float32 strToFloat32(const oatpp::String& str, bool& success);
/**
* String to 64-bit float.
* @param str - string as `const char*`.
* @return - 64-bit float value.
*/
v_float64 strToFloat64(const char* str);
/**
* String to 64-bit float.
* @param str - string as `oatpp::String`.
* @param success - out parameter. `true` if operation was successful. `false` otherwise.
* @return - 64-bit float value.
*/
v_float64 strToFloat64(const oatpp::String& str, bool& success);
/**
* Convert 32-bit float to it's string representation.
* @param value - 32-bit float value.
* @param data - buffer to write data to.
* @param n - buffer size.
* @return - length of the resultant string.
*/
v_buff_size float32ToCharSequence(v_float32 value, p_char8 data, v_buff_size n, const char* format = OATPP_FLOAT_STRING_FORMAT);
/**
* Convert 64-bit float to it's string representation.
* @param value - 64-bit float value.
* @param data - buffer to write data to.
* @param n - buffer size.
* @return - length of the resultant string.
*/
v_buff_size float64ToCharSequence(v_float64 value, p_char8 data, v_buff_size n, const char* format = OATPP_FLOAT_STRING_FORMAT);
/**
* Convert 32-bit float to it's string representation.
* @param value - 32-bit float value.
* @return - value as `oatpp::String`
*/
oatpp::String float32ToStr(v_float32 value, const char* format = OATPP_FLOAT_STRING_FORMAT);
/**
* Convert 64-bit float to it's string representation.
* @param value - 64-bit float value.
* @return - value as `oatpp::String`
*/
oatpp::String float64ToStr(v_float64 value, const char* format = OATPP_FLOAT_STRING_FORMAT);
/**
* Convert boolean to it's string representation.
* @param value - boolean value.
* @return - value as `oatpp::String`;
*/
oatpp::String boolToStr(bool value);
/**
* parse string to boolean value.
* @param str - string to parse.
* @param success - out parameter. `true` if operation was successful. `false` otherwise.
* @return - boolean value.
*/
bool strToBool(const oatpp::String& str, bool& success);
}}}
#endif /* oatpp_utils_ConversionUtils_hpp */
| vincent-in-black-sesame/oat | src/oatpp/core/utils/ConversionUtils.hpp | C++ | apache-2.0 | 9,853 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#include "Random.hpp"
namespace oatpp { namespace utils { namespace random {
#ifndef OATPP_COMPAT_BUILD_NO_THREAD_LOCAL
thread_local std::mt19937 Random::RANDOM_GENERATOR(std::random_device{}());
#else
std::mt19937 Random::RANDOM_GENERATOR (std::random_device{}());
oatpp::concurrency::SpinLock Random::RANDOM_LOCK;
#endif
void Random::randomBytes(p_char8 buffer, v_buff_size bufferSize) {
#if defined(OATPP_COMPAT_BUILD_NO_THREAD_LOCAL)
std::lock_guard<oatpp::concurrency::SpinLock> randomLock(RANDOM_LOCK);
#endif
std::uniform_int_distribution<size_t> distribution(0, 255);
for(v_buff_size i = 0; i < bufferSize; i ++) {
buffer[i] = (v_char8) distribution(RANDOM_GENERATOR);
}
}
}}}
| vincent-in-black-sesame/oat | src/oatpp/core/utils/Random.cpp | C++ | apache-2.0 | 1,707 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef oatpp_utils_Random_hpp
#define oatpp_utils_Random_hpp
#include "oatpp/core/concurrency/SpinLock.hpp"
#include "oatpp/core/Types.hpp"
#include <random>
namespace oatpp { namespace utils { namespace random {
/**
* Utility class for random values.
*/
class Random {
private:
#ifndef OATPP_COMPAT_BUILD_NO_THREAD_LOCAL
static thread_local std::mt19937 RANDOM_GENERATOR;
#else
static std::mt19937 RANDOM_GENERATOR;
static oatpp::concurrency::SpinLock RANDOM_LOCK;
#endif
public:
/**
* Fill in buffer with random bytes [0..255].
* @param buffer - pointer to buffer.
* @param bufferSize - size of the buffer.
*/
static void randomBytes(p_char8 buffer, v_buff_size bufferSize);
};
}}}
#endif // oatpp_utils_Random_hpp
| vincent-in-black-sesame/oat | src/oatpp/core/utils/Random.hpp | C++ | apache-2.0 | 1,745 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#include "String.hpp"
#include <cstring>
namespace oatpp { namespace utils {
v_buff_size String::compare(const void* data1, v_buff_size size1, const void* data2, v_buff_size size2) {
if(data1 == data2) return 0;
if(data1 == nullptr) return -1;
if(data2 == nullptr) return 1;
if(size1 < size2) {
auto res = std::memcmp(data1, data2, size1);
if(res == 0) return -1;
return res;
}
if(size1 > size2) {
auto res = std::memcmp(data1, data2, size2);
if(res == 0) return 1;
return res;
}
return std::memcmp(data1, data2, size1);
}
v_buff_size String::compareCI_ASCII(const void* data1, v_buff_size size1, const void* data2, v_buff_size size2) {
if(data1 == data2) return 0;
if(data1 == nullptr) return -1;
if(data2 == nullptr) return 1;
auto d1 = (p_char8) data1;
auto d2 = (p_char8) data2;
v_buff_size size = size1;
if(size2 < size1) size = size2;
for(v_buff_size i = 0; i < size; i ++) {
v_char8 a = d1[i];
v_char8 b = d2[i];
if(a >= 'A' && a <= 'Z') a |= 32;
if(b >= 'A' && b <= 'Z') b |= 32;
if(a != b) {
return (int) a - (int) b;
}
}
if(size1 < size2) return -1;
if(size1 > size2) return 1;
return 0;
}
void String::lowerCase_ASCII(void* data, v_buff_size size) {
for(v_buff_size i = 0; i < size; i++) {
v_char8 a = ((p_char8) data)[i];
if(a >= 'A' && a <= 'Z') ((p_char8) data)[i] = a | 32;
}
}
void String::upperCase_ASCII(void* data, v_buff_size size) {
for(v_buff_size i = 0; i < size; i++) {
v_char8 a = ((p_char8) data)[i];
if(a >= 'a' && a <= 'z') ((p_char8) data)[i] = a & 223;
}
}
}}
| vincent-in-black-sesame/oat | src/oatpp/core/utils/String.cpp | C++ | apache-2.0 | 2,627 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef oatpp_utils_String_hpp
#define oatpp_utils_String_hpp
#include "oatpp/core/base/Environment.hpp"
namespace oatpp { namespace utils {
/**
* Utility class for Strings
*/
class String {
public:
/**
* Compare data1, data2 using `std::memcmp`.
* *It's safe to pass nullptr for data1/data2*
* @param data1 - pointer to data1.
* @param size1 - size of data1.
* @param data2 - pointer to data2.
* @param size2 - size of data2.
* @return - Negative value if the first differing byte (reinterpreted as unsigned char) in data1 is less than the corresponding byte in data2.<br>
* 0 if all count bytes of data1 and data2 are equal.<br>
* Positive value if the first differing byte in data1 is greater than the corresponding byte in data2.
*/
static v_buff_size compare(const void* data1, v_buff_size size1, const void* data2, v_buff_size size2);
/**
* Compare data1, data2 - case insensitive (ASCII only).
* *It's safe to pass nullptr for data1/data2*
* @param data1 - pointer to data1.
* @param size1 - size of data1.
* @param data2 - pointer to data2.
* @param size2 - size of data2.
* @return - Negative value if the first differing byte (reinterpreted as unsigned char) in data1 is less than the corresponding byte in data2.<br>
* 0 if all count bytes of data1 and data2 are equal.<br>
* Positive value if the first differing byte in data1 is greater than the corresponding byte in data2.
*/
static v_buff_size compareCI_ASCII(const void* data1, v_buff_size size1, const void* data2, v_buff_size size2);
/**
* Change characters in data to lowercase (ASCII only).
* @param data - pointer to data.
* @param size - size of the data.
*/
static void lowerCase_ASCII(void* data, v_buff_size size);
/**
* Change characters in data to uppercase (ASCII only).
* @param data - pointer to data.
* @param size - size of the data.
*/
static void upperCase_ASCII(void* data, v_buff_size size);
};
}}
#endif // oatpp_utils_String_hpp
| vincent-in-black-sesame/oat | src/oatpp/core/utils/String.hpp | C++ | apache-2.0 | 3,026 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#include "Base64.hpp"
namespace oatpp { namespace encoding {
const char* const Base64::ALPHABET_BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
const char* const Base64::ALPHABET_BASE64_URL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=";
const char* const Base64::ALPHABET_BASE64_URL_SAFE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._-";
const char* const Base64::ALPHABET_BASE64_AUXILIARY_CHARS = "+/=";
const char* const Base64::ALPHABET_BASE64_URL_AUXILIARY_CHARS = "-_=";
const char* const Base64::ALPHABET_BASE64_URL_SAFE_AUXILIARY_CHARS = "._-";
v_char8 Base64::getAlphabetCharIndex(v_char8 a, const char* auxiliaryChars) {
if(a >= 'A' && a <='Z') {
return a - 'A';
}
if(a >= 'a' && a <='z') {
return a - 'a' + 26;
}
if(a >= '0' && a <='9') {
return a - '0' + 52;
}
if(a == auxiliaryChars[0]) {
return 62;
}
if(a == auxiliaryChars[1]) {
return 63;
}
return 255;
}
v_buff_size Base64::calcEncodedStringSize(v_buff_size size) {
v_buff_size size3 = size / 3;
v_buff_size rSize = size3 * 3;
if(rSize < size){
rSize += 4;
}
return rSize + size3; // resultSize = (size3 * 3 + size3) = size3 * 4
}
v_buff_size Base64::calcDecodedStringSize(const char* data, v_buff_size size, v_buff_size& base64StrLength, const char* auxiliaryChars) {
base64StrLength = size;
v_char8 auxChar1 = auxiliaryChars[0];
v_char8 auxChar2 = auxiliaryChars[1];
v_char8 paddingChar = auxiliaryChars[2];
v_buff_size i = 0;
while (i < size) {
v_char8 a = data[i];
bool isValidChar = (a >= 'A' && a <='Z') || (a >= 'a' && a <='z') || (a >= '0' && a <='9') || (a == auxChar1) || (a == auxChar2);
if(!isValidChar) {
if(a == paddingChar){
base64StrLength = i;
break;
}
return -1;
}
i++;
}
v_buff_size size4 = i >> 2;
v_buff_size size4d = i - (size4 << 2);
v_buff_size resultSize = size4 * 3;
if(size4d > 0) {
resultSize += size4d - 1;
}
return resultSize;
}
bool Base64::isBase64String(const char* data, v_buff_size size, const char* auxiliaryChars) {
v_buff_size base64StrLength;
return (calcDecodedStringSize(data, size, base64StrLength, auxiliaryChars) >= 0);
}
oatpp::String Base64::encode(const void* data, v_buff_size size, const char* alphabet) {
auto resultSize = calcEncodedStringSize(size);
auto result = oatpp::String(resultSize);
p_char8 bdata = (p_char8) data;
p_char8 resultData = (p_char8) result->data();
v_buff_size pos = 0;
while (pos + 2 < size) {
v_char8 b0 = bdata[pos];
v_char8 b1 = bdata[pos + 1];
v_char8 b2 = bdata[pos + 2];
resultData[0] = alphabet[(b0 & 252) >> 2];
resultData[1] = alphabet[((b0 & 3) << 4) | ((b1 >> 4) & 15)];
resultData[2] = alphabet[((b1 & 15) << 2) | ((b2 >> 6) & 3)];
resultData[3] = alphabet[(b2 & 63)];
resultData += 4;
pos += 3;
}
if(pos + 1 < size) {
v_char8 b0 = bdata[pos];
v_char8 b1 = bdata[pos + 1];
resultData[0] = alphabet[(b0 & 252) >> 2];
resultData[1] = alphabet[((b0 & 3) << 4) | ((b1 >> 4) & 15)];
resultData[2] = alphabet[((b1 & 15) << 2)];
resultData[3] = alphabet[64];
} else if(pos < size) {
v_char8 b0 = bdata[pos];
resultData[0] = alphabet[(b0 & 252) >> 2];
resultData[1] = alphabet[(b0 & 3) << 4];
resultData[2] = alphabet[64];
resultData[3] = alphabet[64];
}
return result;
}
oatpp::String Base64::encode(const oatpp::String& data, const char* alphabet) {
return encode(data->data(), data->size(), alphabet);
}
oatpp::String Base64::decode(const char* data, v_buff_size size, const char* auxiliaryChars) {
v_buff_size base64StrLength;
auto resultSize = calcDecodedStringSize(data, size, base64StrLength, auxiliaryChars);
if(resultSize < 0) {
throw DecodingError("Data is no base64 string. Make sure that auxiliaryChars match with encoder alphabet");
}
auto result = oatpp::String(resultSize);
p_char8 resultData = (p_char8) result->data();
v_buff_size pos = 0;
while (pos + 3 < base64StrLength) {
v_char8 b0 = getAlphabetCharIndex(data[pos], auxiliaryChars);
v_char8 b1 = getAlphabetCharIndex(data[pos + 1], auxiliaryChars);
v_char8 b2 = getAlphabetCharIndex(data[pos + 2], auxiliaryChars);
v_char8 b3 = getAlphabetCharIndex(data[pos + 3], auxiliaryChars);
resultData[0] = (b0 << 2) | ((b1 >> 4) & 3);
resultData[1] = ((b1 & 15) << 4) | ((b2 >> 2) & 15);
resultData[2] = ((b2 & 3) << 6) | b3;
resultData += 3;
pos += 4;
}
v_buff_size posDiff = base64StrLength - pos;
if(posDiff == 3) {
v_char8 b0 = getAlphabetCharIndex(data[pos], auxiliaryChars);
v_char8 b1 = getAlphabetCharIndex(data[pos + 1], auxiliaryChars);
v_char8 b2 = getAlphabetCharIndex(data[pos + 2], auxiliaryChars);
resultData[0] = (b0 << 2) | ((b1 >> 4) & 3);
resultData[1] = ((b1 & 15) << 4) | ((b2 >> 2) & 15);
} else if(posDiff == 2) {
v_char8 b0 = getAlphabetCharIndex(data[pos], auxiliaryChars);
v_char8 b1 = getAlphabetCharIndex(data[pos + 1], auxiliaryChars);
resultData[0] = (b0 << 2) | ((b1 >> 4) & 3);
}
return result;
}
oatpp::String Base64::decode(const oatpp::String& data, const char* auxiliaryChars) {
return decode((const char*)data->data(), data->size(), auxiliaryChars);
}
}}
| vincent-in-black-sesame/oat | src/oatpp/encoding/Base64.cpp | C++ | apache-2.0 | 6,443 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef oatpp_encoding_Base64_hpp
#define oatpp_encoding_Base64_hpp
#include "oatpp/core/Types.hpp"
namespace oatpp { namespace encoding {
/**
* Base64 - encoder/decoder.
*/
class Base64 {
public:
/**
* DecodingError.
*/
class DecodingError : public std::runtime_error {
public:
/**
* Constructor.
* @param message - error message.
*/
DecodingError(const char* message)
:std::runtime_error(message)
{}
};
private:
static v_char8 getAlphabetCharIndex(v_char8 a, const char* auxiliaryChars);
public:
/**
* Standard base64 Alphabet - `['A'-'Z', 'a'-'z', '0'-'9', '+', '/', '=']`.
* Alphabet is array of 65 chars. 64 chars encoding chars, and 65th padding char.<br>
*/
static const char* const ALPHABET_BASE64;
/**
* URL base64 Alphabet - `['A'-'Z', 'a'-'z', '0'-'9', '-', '_', '=']`.
* Alphabet is array of 65 chars. 64 chars encoding chars, and 65th padding char.<br>
*/
static const char* const ALPHABET_BASE64_URL;
/**
* URL safe base64 Alphabet - `['A'-'Z', 'a'-'z', '0'-'9', '.', '_', '-']`.
* Alphabet is array of 65 chars. 64 chars encoding chars, and 65th padding char.<br>
*/
static const char* const ALPHABET_BASE64_URL_SAFE;
/**
* Standard base64 Alphabet auxiliary chars ['+', '/', '='].
* alphabet auxiliary chars - last 3 chars of alphabet including padding char.
*/
static const char* const ALPHABET_BASE64_AUXILIARY_CHARS;
/**
* URL base64 Alphabet auxiliary chars ['-', '_', '='].
* alphabet auxiliary chars - last 3 chars of alphabet including padding char.
*/
static const char* const ALPHABET_BASE64_URL_AUXILIARY_CHARS;
/**
* URL safe base64 Alphabet auxiliary chars ['.', '_', '='].
* alphabet auxiliary chars - last 3 chars of alphabet including padding char.
*/
static const char* const ALPHABET_BASE64_URL_SAFE_AUXILIARY_CHARS;
/**
* Calculate size of encoding result of a string of the given size.
* @param size - size of string to encode.
* @return - size of encoding result of a string of the given size
*/
static v_buff_size calcEncodedStringSize(v_buff_size size);
/**
* Calculate size of decoding result. this method assumes that data passed as a param consists of standard base64 set of chars
* `['A'-'Z', 'a'-'z', '0'-'9']` and three configurable auxiliary chars.
* @param data - pointer to data.
* @param size - size of the data.
* @param base64StrLength - out parameter. Size of base64 valid encoded string. It may appear to be less then size.
* @param auxiliaryChars - configurable auxiliary chars.
* @return - size of decoded data. If data passed is not a base64 string then -1 is returned.
*/
static v_buff_size calcDecodedStringSize(const char* data, v_buff_size size, v_buff_size& base64StrLength, const char* auxiliaryChars = ALPHABET_BASE64_AUXILIARY_CHARS);
/**
* Check if data is a valid base64 encoded string.
* @param data - pointer to data.
* @param size - data size.
* @param auxiliaryChars - configurable auxiliary chars.
* @return `(calcDecodedStringSize(data, size, base64StrLength, auxiliaryChars) >= 0)`.
*/
static bool isBase64String(const char* data, v_buff_size size, const char* auxiliaryChars = ALPHABET_BASE64_AUXILIARY_CHARS);
/**
* Encode data as base64 string.
* @param data - pointer to data.
* @param size - data size.
* @param alphabet - base64 alphabet to use.
* @return - encoded base64 string as &id:oatpp::String;.
*/
static oatpp::String encode(const void* data, v_buff_size size, const char* alphabet = ALPHABET_BASE64);
/**
* Encode data as base64 string.
* @param data - data to encode.
* @param alphabet - base64 alphabet to use.
* @return - encoded base64 string as &id:oatpp::String;.
*/
static oatpp::String encode(const oatpp::String& data, const char* alphabet = ALPHABET_BASE64);
/**
* Decode base64 encoded data. This method assumes that data passed as a param consists of standard base64 set of chars
* `['A'-'Z', 'a'-'z', '0'-'9']` and three configurable auxiliary chars.
* @param data - pointer to data to decode.
* @param size - encoded data size.
* @param auxiliaryChars - configurable auxiliary chars.
* @return - decoded data as &id:oatpp::String;.
* @throws - &l:Base64::DecodingError;
*/
static oatpp::String decode(const char* data, v_buff_size size, const char* auxiliaryChars = ALPHABET_BASE64_AUXILIARY_CHARS);
/**
* Decode base64 encoded data. This method assumes that data passed as a param consists of standard base64 set of chars
* `['A'-'Z', 'a'-'z', '0'-'9']` and three configurable auxiliary chars.
* @param data - data to decode.
* @param auxiliaryChars - configurable auxiliary chars.
* @return - decoded data as &id:oatpp::String;.
* @throws - &l:Base64::DecodingError;
*/
static oatpp::String decode(const oatpp::String& data, const char* auxiliaryChars = ALPHABET_BASE64_AUXILIARY_CHARS);
};
}}
#endif /* oatpp_encoding_Base64_hpp */
| vincent-in-black-sesame/oat | src/oatpp/encoding/Base64.hpp | C++ | apache-2.0 | 6,064 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#include "Hex.hpp"
#if defined(WIN32) || defined(_WIN32)
#include <WinSock2.h>
#else
#include <arpa/inet.h>
#endif
namespace oatpp { namespace encoding {
const char* Hex::ALPHABET_UPPER = "0123456789ABCDEF";
const char* Hex::ALPHABET_LOWER = "0123456789abcdef";
void Hex::writeUInt16(v_uint16 value, p_char8 buffer){
*((p_uint32) buffer) = htonl((ALPHABET_UPPER[ value & 0x000F ] ) |
(ALPHABET_UPPER[(value & 0x00F0) >> 4] << 8) |
(ALPHABET_UPPER[(value & 0x0F00) >> 8] << 16) |
(ALPHABET_UPPER[(value & 0xF000) >> 12] << 24));
}
void Hex::writeUInt32(v_uint32 value, p_char8 buffer){
writeUInt16(value >> 16, buffer);
writeUInt16(v_uint16(value), buffer + 4);
}
v_int32 Hex::readUInt16(const char* buffer, v_uint16& value) {
value = 0;
for(v_int32 i = 0; i < 4; i++){
v_char8 a = buffer[i];
if(a >= '0' && a <= '9') {
value |= (a - '0') << ((3 - i) << 2);
} else if (a >= 'A' && a <= 'F') {
value |= (a - 'A' + 10) << ((3 - i) << 2);
} else if (a >= 'a' && a <= 'f') {
value |= (a - 'a' + 10) << ((3 - i) << 2);
} else {
return ERROR_UNKNOWN_SYMBOL;
}
}
return 0;
}
v_int32 Hex::readUInt32(const char* buffer, v_uint32& value) {
value = 0;
for(v_int32 i = 0; i < 8; i++){
v_char8 a = buffer[i];
if(a >= '0' && a <= '9') {
value |= (a - '0') << ((7 - i) << 2);
} else if (a >= 'A' && a <= 'F') {
value |= (a - 'A' + 10) << ((7 - i) << 2);
} else if (a >= 'a' && a <= 'f') {
value |= (a - 'a' + 10) << ((7 - i) << 2);
} else {
return ERROR_UNKNOWN_SYMBOL;
}
}
return 0;
}
void Hex::encode(data::stream::ConsistentOutputStream* stream,
const void* data, v_buff_size size,
const char* alphabet)
{
p_char8 buffer = (p_char8) data;
v_char8 oneByteBuffer[2];
for(v_buff_size i = 0; i < size; i ++) {
auto c = buffer[i];
v_char8 b1 = 0x0F & (c >> 4);
v_char8 b2 = 0x0F & (c);
oneByteBuffer[0] = alphabet[b1];
oneByteBuffer[1] = alphabet[b2];
stream->writeSimple(oneByteBuffer, 2);
}
}
void Hex::decode(data::stream::ConsistentOutputStream* stream,
const void* data, v_buff_size size, bool allowSeparators)
{
p_char8 buffer = (p_char8) data;
v_char8 byte = 0;
v_int32 shift = 4;
for(v_buff_size i = 0; i < size; i ++) {
auto a = buffer[i];
if(a >= '0' && a <= '9') {
byte |= (a - '0') << shift;
shift -= 4;
} else if (a >= 'A' && a <= 'F') {
byte |= (a - 'A' + 10) << shift;
shift -= 4;
} else if (a >= 'a' && a <= 'f') {
byte |= (a - 'a' + 10) << shift;
shift -= 4;
} else if(!allowSeparators) {
throw DecodingError("Invalid Character");
}
if(shift < 0) {
stream->writeCharSimple(byte);
byte = 0;
shift = 4;
}
}
if(shift != 4) {
throw DecodingError("Invalid input data size");
}
}
}}
| vincent-in-black-sesame/oat | src/oatpp/encoding/Hex.cpp | C++ | apache-2.0 | 4,026 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef oatpp_encoding_Hex_hpp
#define oatpp_encoding_Hex_hpp
#include "oatpp/core/data/stream/Stream.hpp"
#include "oatpp/core/Types.hpp"
namespace oatpp { namespace encoding {
/**
* Utility class for hex string encoding/decoding .
*/
class Hex {
public:
static const char* ALPHABET_UPPER;
static const char* ALPHABET_LOWER;
public:
/**
* Unknown symbol error.
*/
static constexpr v_int32 ERROR_UNKNOWN_SYMBOL = 1;
public:
/**
* DecodingError.
*/
class DecodingError : public std::runtime_error {
public:
/**
* Constructor.
* @param message - error message.
*/
DecodingError(const char* message)
:std::runtime_error(message)
{}
};
public:
/**
* Write value as hex string to buffer.
* @param value - value to write.
* @param buffer - buffer for resultant string.
*/
static void writeUInt16(v_uint16 value, p_char8 buffer);
/**
* Write value as hex string to buffer.
* @param value - value to write.
* @param buffer - buffer for resultant string.
*/
static void writeUInt32(v_uint32 value, p_char8 buffer);
/**
* Parse 4-char hex string to int16.
* @param buffer - buffer containing string to parse.
* @param value - out parameter. Resultant value.
* @return - 0 on success. Negative value on failure.
*/
static v_int32 readUInt16(const char* buffer, v_uint16& value);
/**
* Parse 8-char hex string to int32.
* @param buffer - buffer containing string to parse.
* @param value - out parameter. Resultant value.
* @return - 0 on success. Negative value on failure.
*/
static v_int32 readUInt32(const char* buffer, v_uint32& value);
/**
* Write binary data as HEX string.
* @param stream
* @param data
* @param size
* @param alphabet
*/
static void encode(data::stream::ConsistentOutputStream* stream,
const void* data, v_buff_size size,
const char* alphabet = ALPHABET_UPPER);
/**
* Read binary data from hex string.
* @param stream
* @param data
* @param size
* @param allowSeparators - skip any char which is not ([A-Z], [a-z], [0-9]) without error.
* @throws - &l:Hex::DecodingError;
*/
static void decode(data::stream::ConsistentOutputStream* stream,
const void* data, v_buff_size size, bool allowSeparators = false);
};
}}
#endif /* oatpp_encoding_Hex_hpp */
| vincent-in-black-sesame/oat | src/oatpp/encoding/Hex.hpp | C++ | apache-2.0 | 3,421 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#include "Unicode.hpp"
#if defined(WIN32) || defined(_WIN32)
#include <Winsock2.h>
#else
#include <arpa/inet.h>
#endif
namespace oatpp { namespace encoding {
v_buff_size Unicode::getUtf8CharSequenceLength(v_char8 firstByte) {
if(firstByte < 128){
return 1;
}
if((firstByte | 192) != firstByte){
return 0;
}
if((firstByte | 32) != firstByte){
return 2;
} else if((firstByte | 16) != firstByte){
return 3;
} else if((firstByte | 8) != firstByte){
return 4;
} else if((firstByte | 4) != firstByte){
return 5;
} else if((firstByte | 2) != firstByte){
return 6;
} else {
return 0;
}
}
v_buff_size Unicode::getUtf8CharSequenceLengthForCode(v_uint32 code){
if(code < 128) {
return 1;
} else if(code < 0x00000800){
return 2;
} else if(code < 0x00010000){
return 3;
} else if(code < 0x00200000){
return 4;
} else if(code < 0x04000000){
return 5;
} else {
return 6;
}
}
v_int32 Unicode::encodeUtf8Char(const char* sequence, v_buff_size& length){
v_char8 byte = sequence[0];
if(byte > 127){
v_int32 code;
if((byte | 32) != byte){
length = 2;
code = ((31 & byte) << 6) | (sequence[1] & 63);
return code;
} else if((byte | 16) != byte){
code = (15 & byte) << 12;
length = 3;
} else if((byte | 8) != byte){
length = 4;
v_int32 value = *((p_int32)sequence);
code = ((7 & byte) << 18) |
(((value >> 24) & 0xFF) & 63) |
(((value >> 16) & 0xFF) & 63) << 6 |
(((value >> 8) & 0xFF) & 63) << 12;
return code;
} else if((byte | 4) != byte){
code = (3 & byte) << 24;
length = 5;
} else if((byte | 2) != byte){
code = (1 & byte) << 30;
length = 6;
} else {
return -1;
}
v_char8 bitIndex = 0;
for(v_buff_size i = length; i > 1; i--){
code |= (sequence[i - 1] & 63) << bitIndex;
bitIndex += 6;
}
return code;
} else {
length = 1;
return byte;
}
}
v_buff_size Unicode::decodeUtf8Char(v_int32 code, p_char8 buffer) {
if(code >= 0x00000080 && code < 0x00000800){
*((p_int16) buffer) = htons(((((code >> 6) & 31) | 192) << 8) | ((code & 63) | 128));
return 2;
} else if(code >= 0x00000800 && code < 0x00010000){
*((p_int16) buffer) = htons((((( code >> 12 ) & 15) | 224) << 8) |
(((code >> 6 ) & 63) | 128));
buffer[2] = (code & 63) | 128;
return 3;
} else if(code >= 0x00010000 && code < 0x00200000){
*((p_int32) buffer) = htonl(((((code >> 18 ) & 7) | 240) << 24) |
((((code >> 12 ) & 63) | 128) << 16) |
((((code >> 6 ) & 63) | 128) << 8) |
(( code & 63) | 128) );
return 4;
} else if(code >= 0x00200000 && code < 0x04000000){
*((p_int32) buffer) = htonl(((((code >> 24 ) & 3) | 248) << 24) |
((((code >> 18 ) & 63) | 128) << 16) |
((((code >> 12 ) & 63) | 128) << 8) |
(((code >> 6 ) & 63) | 128));
buffer[4] = (code & 63) | 128;
return 5;
} else if(code >= 0x04000000){
*((p_int32) buffer) = htonl(((((code >> 30 ) & 1) | 252) << 24) |
((((code >> 24 ) & 63) | 128) << 16) |
((((code >> 18 ) & 63) | 128) << 8) |
(((code >> 12 ) & 63) | 128));
*((p_int16) &buffer[4]) = htons(((((code >> 6 ) & 63) | 128) << 8) | (code & 63));
return 6;
}
buffer[0] = v_char8(code);
return 1;
}
void Unicode::codeToUtf16SurrogatePair(v_int32 code, v_int16& high, v_int16& low){
code -= 0x010000;
high = 0xD800 + ((code >> 10) & 1023);
low = 0xDC00 + (code & 1023);
}
v_int32 Unicode::utf16SurrogatePairToCode(v_int16 high, v_int16 low){
return (((low - 0xDC00) & 1023) | (((high - 0xD800) & 1023) << 10)) + 0x010000;
}
}}
| vincent-in-black-sesame/oat | src/oatpp/encoding/Unicode.cpp | C++ | apache-2.0 | 5,065 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef oatpp_encoding_Unicode_hpp
#define oatpp_encoding_Unicode_hpp
#include "oatpp/core/base/Environment.hpp"
namespace oatpp { namespace encoding {
/**
* Helper class for processing unicode characters.
*/
class Unicode {
public:
/**
* Get length in bytes of UTF-8 character by its first byte.
* @param firstByte - first byte of UTF-8 character.
* @return - length in bytes of UTF-8 character.
*/
static v_buff_size getUtf8CharSequenceLength(v_char8 firstByte);
/**
* Get length in bytes of UTF-8 character by its code.
* @param code - code of UTF-8 character.
* @return - length in bytes of UTF-8 character.
*/
static v_buff_size getUtf8CharSequenceLengthForCode(v_uint32 code);
/**
* Get code of UTF-8 character.
* @param sequence - pointer to first byte of UTF-8 character.
* @param length - out parameter. Length in bytes of UTF-8 character.
* @return - code of UTF-8 character.
*/
static v_int32 encodeUtf8Char(const char* sequence, v_buff_size& length);
/**
* Write UTF-8 character to buffer.
* @param code - UTF-8 character code.
* @param buffer - pointer to write UTF-8 character to.
* @return - length in bytes of UTF-8 character.
*/
static v_buff_size decodeUtf8Char(v_int32 code, p_char8 buffer);
/**
* Get corresponding UTF-16 surrogate pair for symbol code.
* @param code - symbol code.
* @param high - out parameter. High surrogate.
* @param low - out parameter. Low surrogate.
*/
static void codeToUtf16SurrogatePair(v_int32 code, v_int16& high, v_int16& low);
/**
* Get symbol code of corresponding UTF-16 surrogate pair.
* @param high - High surrogate.
* @param low - Low surrogate.
* @return - symbol code.
*/
static v_int32 utf16SurrogatePairToCode(v_int16 high, v_int16 low);
};
}}
#endif /* oatpp_encoding_Unicode_hpp */
| vincent-in-black-sesame/oat | src/oatpp/encoding/Unicode.hpp | C++ | apache-2.0 | 2,864 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#include "Address.hpp"
namespace oatpp { namespace network {
Address::Address(const oatpp::String& pHost, v_uint16 pPort, Family pFamily)
: host(pHost)
, port(pPort)
, family(pFamily)
{}
}}
| vincent-in-black-sesame/oat | src/oatpp/network/Address.cpp | C++ | apache-2.0 | 1,195 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef oatpp_network_Address_hpp
#define oatpp_network_Address_hpp
#include "oatpp/core/Types.hpp"
namespace oatpp { namespace network {
/**
* Network address.
*/
class Address {
public:
/**
* Address family.
*/
enum Family : v_int32 {
/**
* IPv4.
*/
IP_4 = 0,
/**
* IPv6.
*/
IP_6 = 1,
/**
* Unspecified.
*/
UNSPEC = 2
};
public:
/**
* Constructor.
* @param pHost
* @param pPort
* @param pFamily
*/
Address(const oatpp::String& pHost, v_uint16 pPort, Family pFamily = UNSPEC);
/**
* Host name without schema and port. Ex.: "oatpp.io", "127.0.0.1", "localhost".
*/
oatpp::String host;
/**
* Port.
*/
v_uint16 port;
/**
* Family &l:Address::Family;.
*/
Family family;
};
}}
#endif // oatpp_network_Address_hpp
| vincent-in-black-sesame/oat | src/oatpp/network/Address.hpp | C++ | apache-2.0 | 1,837 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef oatpp_network_ConnectionHandler_hpp
#define oatpp_network_ConnectionHandler_hpp
#include "oatpp/core/provider/Provider.hpp"
#include "oatpp/core/data/stream/Stream.hpp"
#include <unordered_map>
namespace oatpp { namespace network {
/**
* Abstract ConnectionHandler.
*/
class ConnectionHandler {
public:
/**
* Convenience typedef for &id:oatpp::data::stream::IOStream;.
*/
typedef oatpp::data::stream::IOStream IOStream;
/**
* Convenience typedef for accompanying parameters of connection handling.
*/
typedef std::unordered_map<oatpp::String, oatpp::String> ParameterMap;
public:
/**
* Virtual Destructor.
*/
virtual ~ConnectionHandler() = default;
/**
* Handle provided connection.
* @param connectionData - see &id:oatpp::data::stream::IOStream;.
* @param params - accompanying parameters.
*/
virtual void handleConnection(const provider::ResourceHandle<IOStream>& connectionData,
const std::shared_ptr<const ParameterMap>& params) = 0;
/**
* Stop all threads here
*/
virtual void stop() = 0;
};
}}
#endif /* oatpp_network_ConnectionHandler_hpp */
| vincent-in-black-sesame/oat | src/oatpp/network/ConnectionHandler.hpp | C++ | apache-2.0 | 2,155 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#include "ConnectionPool.hpp"
namespace oatpp { namespace network {
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ConnectionAcquisitionProxy
v_io_size ConnectionAcquisitionProxy::write(const void *buff, v_buff_size count, async::Action& action) {
return _handle.object->write(buff, count, action);
}
v_io_size ConnectionAcquisitionProxy::read(void *buff, v_buff_size count, async::Action& action) {
return _handle.object->read(buff, count, action);
}
void ConnectionAcquisitionProxy::setOutputStreamIOMode(oatpp::data::stream::IOMode ioMode) {
return _handle.object->setOutputStreamIOMode(ioMode);
}
oatpp::data::stream::IOMode ConnectionAcquisitionProxy::getOutputStreamIOMode() {
return _handle.object->getOutputStreamIOMode();
}
void ConnectionAcquisitionProxy::setInputStreamIOMode(oatpp::data::stream::IOMode ioMode) {
return _handle.object->setInputStreamIOMode(ioMode);
}
oatpp::data::stream::IOMode ConnectionAcquisitionProxy::getInputStreamIOMode() {
return _handle.object->getInputStreamIOMode();
}
oatpp::data::stream::Context& ConnectionAcquisitionProxy::getOutputStreamContext() {
return _handle.object->getOutputStreamContext();
}
oatpp::data::stream::Context& ConnectionAcquisitionProxy::getInputStreamContext() {
return _handle.object->getInputStreamContext();
}
}}
| vincent-in-black-sesame/oat | src/oatpp/network/ConnectionPool.cpp | C++ | apache-2.0 | 2,383 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef oatpp_network_ConnectionPool_hpp
#define oatpp_network_ConnectionPool_hpp
#include "ConnectionProvider.hpp"
#include "oatpp/core/provider/Pool.hpp"
namespace oatpp { namespace network {
/**
* Wrapper over &id:oatpp::data::stream::IOStream;.
* Will acquire connection from the pool on initialization and will return connection to the pool on destruction.
*/
struct ConnectionAcquisitionProxy : public provider::AcquisitionProxy<data::stream::IOStream, ConnectionAcquisitionProxy> {
ConnectionAcquisitionProxy(const provider::ResourceHandle<data::stream::IOStream>& resource,
const std::shared_ptr<PoolInstance>& pool)
: provider::AcquisitionProxy<data::stream::IOStream, ConnectionAcquisitionProxy>(resource, pool)
{}
v_io_size write(const void *buff, v_buff_size count, async::Action& action) override;
v_io_size read(void *buff, v_buff_size count, async::Action& action) override;
void setOutputStreamIOMode(oatpp::data::stream::IOMode ioMode) override;
oatpp::data::stream::IOMode getOutputStreamIOMode() override;
void setInputStreamIOMode(oatpp::data::stream::IOMode ioMode) override;
oatpp::data::stream::IOMode getInputStreamIOMode() override;
oatpp::data::stream::Context& getOutputStreamContext() override;
oatpp::data::stream::Context& getInputStreamContext() override;
};
typedef oatpp::provider::Pool<
oatpp::network::ClientConnectionProvider,
oatpp::data::stream::IOStream,
oatpp::network::ConnectionAcquisitionProxy
> ClientConnectionPool;
typedef oatpp::provider::Pool<
oatpp::network::ServerConnectionProvider,
oatpp::data::stream::IOStream,
oatpp::network::ConnectionAcquisitionProxy
> ServerConnectionPool;
}}
#endif // oatpp_network_ConnectionPool_hpp
| vincent-in-black-sesame/oat | src/oatpp/network/ConnectionPool.hpp | C++ | apache-2.0 | 2,756 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#include "./ConnectionProvider.hpp"
namespace oatpp { namespace network {
const char* const ConnectionProvider::PROPERTY_HOST = "host";
const char* const ConnectionProvider::PROPERTY_PORT = "port";
}}
| vincent-in-black-sesame/oat | src/oatpp/network/ConnectionProvider.cpp | C++ | apache-2.0 | 1,204 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef oatpp_network_ConnectionProvider_hpp
#define oatpp_network_ConnectionProvider_hpp
#include "oatpp/core/data/share/MemoryLabel.hpp"
#include "oatpp/core/data/stream/Stream.hpp"
#include "oatpp/core/provider/Provider.hpp"
#include <unordered_map>
namespace oatpp { namespace network {
/**
* Abstract ConnectionProvider. <br>
* Basically it returns whatever stream (&id:oatpp::data::stream::IOStream;). <br>
* User of ConnectionProvider should care about IOStream only.
* All other properties are optional.
*/
class ConnectionProvider : public provider::Provider<data::stream::IOStream> {
public:
/**
* Predefined property key for HOST.
*/
static const char* const PROPERTY_HOST;
/**
* Predefined property key for PORT.
*/
static const char* const PROPERTY_PORT;
};
/**
* No properties here. It is just a logical division
*/
class ServerConnectionProvider : virtual public ConnectionProvider {
};
/**
* No properties here. It is just a logical division
*/
class ClientConnectionProvider : virtual public ConnectionProvider {
};
}}
#endif /* oatpp_network_ConnectionProvider_hpp */
| vincent-in-black-sesame/oat | src/oatpp/network/ConnectionProvider.hpp | C++ | apache-2.0 | 2,126 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#include "ConnectionProviderSwitch.hpp"
namespace oatpp { namespace network {
ConnectionProviderSwitch::ConnectionProviderSwitch(const std::shared_ptr<ConnectionProvider>& provider)
: m_provider(provider)
{}
void ConnectionProviderSwitch::resetProvider(const std::shared_ptr<ConnectionProvider>& provider) {
std::lock_guard<std::mutex> lock(m_mutex);
m_provider = provider;
m_properties = provider->getProperties();
}
std::shared_ptr<ConnectionProvider> ConnectionProviderSwitch::getCurrentProvider() {
std::shared_ptr<ConnectionProvider> provider;
{
std::lock_guard<std::mutex> lock(m_mutex);
provider = m_provider;
}
if(!provider) {
const char* const TAG = "[oatpp::network::ConnectionProviderSwitch::getCurrentProvider()]";
const char* const msg = "Error. Can't provide connection. There is no provider set.";
OATPP_LOGE(TAG, msg)
throw std::runtime_error(std::string(TAG) + ": " + msg);
}
return provider;
}
provider::ResourceHandle<data::stream::IOStream> ConnectionProviderSwitch::get() {
return getCurrentProvider()->get();
}
oatpp::async::CoroutineStarterForResult<const provider::ResourceHandle<data::stream::IOStream>&> ConnectionProviderSwitch::getAsync() {
return getCurrentProvider()->getAsync();
}
void ConnectionProviderSwitch::stop() {
return getCurrentProvider()->stop();
}
}}
| vincent-in-black-sesame/oat | src/oatpp/network/ConnectionProviderSwitch.cpp | C++ | apache-2.0 | 2,355 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef oatpp_network_ConnectionProviderSwitch_hpp
#define oatpp_network_ConnectionProviderSwitch_hpp
#include "ConnectionProvider.hpp"
#include <mutex>
namespace oatpp { namespace network {
/**
* ConnectionProviderSwitch can be used to hot-change connection providers.
* Ex.: to hot-reload server certificate.
*/
class ConnectionProviderSwitch : public ServerConnectionProvider, public ClientConnectionProvider {
private:
std::shared_ptr<ConnectionProvider> getCurrentProvider();
private:
std::shared_ptr<ConnectionProvider> m_provider;
std::mutex m_mutex;
public:
/**
* Default constructor.
*/
ConnectionProviderSwitch() = default;
/**
* Constructor.
* @param provider
*/
ConnectionProviderSwitch(const std::shared_ptr<ConnectionProvider>& provider);
/**
* Reset current provider.
* @param provider
*/
void resetProvider(const std::shared_ptr<ConnectionProvider>& provider);
/**
* Get new connection.
* @return &id:oatpp::data::stream::IOStream;.
*/
provider::ResourceHandle<data::stream::IOStream> get() override;
/**
* Get new connection.
* @return &id:oatpp::data::stream::IOStream;.
*/
oatpp::async::CoroutineStarterForResult<const provider::ResourceHandle<data::stream::IOStream>&> getAsync() override;
/**
* Stop current provider.
*/
void stop() override;
};
}}
#endif //oatpp_network_ConnectionProviderSwitch_hpp
| vincent-in-black-sesame/oat | src/oatpp/network/ConnectionProviderSwitch.hpp | C++ | apache-2.0 | 2,411 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#include "Server.hpp"
#include <thread>
#include <chrono>
namespace oatpp { namespace network {
const v_int32 Server::STATUS_CREATED = 0;
const v_int32 Server::STATUS_STARTING = 1;
const v_int32 Server::STATUS_RUNNING = 2;
const v_int32 Server::STATUS_STOPPING = 3;
const v_int32 Server::STATUS_DONE = 4;
Server::Server(const std::shared_ptr<ConnectionProvider> &connectionProvider,
const std::shared_ptr<ConnectionHandler> &connectionHandler)
: m_status(STATUS_CREATED)
, m_connectionProvider(connectionProvider)
, m_connectionHandler(connectionHandler)
, m_threaded(false) {}
// This isn't implemented as static since threading is dropped and therefore static isn't needed anymore.
void Server::conditionalMainLoop() {
setStatus(STATUS_STARTING, STATUS_RUNNING);
std::shared_ptr<const std::unordered_map<oatpp::String, oatpp::String>> params;
while (getStatus() == STATUS_RUNNING) {
if (m_condition()) {
auto connectionHandle = m_connectionProvider->get();
if (connectionHandle.object) {
if (getStatus() == STATUS_RUNNING) {
if (m_condition()) {
m_connectionHandler->handleConnection(connectionHandle, params /* null params */);
} else {
setStatus(STATUS_STOPPING);
}
} else {
OATPP_LOGD("[oatpp::network::server::mainLoop()]", "Error. Server already stopped - closing connection...");
}
}
} else {
setStatus(STATUS_STOPPING);
}
}
setStatus(STATUS_DONE);
}
void Server::mainLoop(Server *instance) {
instance->setStatus(STATUS_STARTING, STATUS_RUNNING);
std::shared_ptr<const std::unordered_map<oatpp::String, oatpp::String>> params;
while (instance->getStatus() == STATUS_RUNNING) {
auto connectionHandle = instance->m_connectionProvider->get();
if (connectionHandle) {
if (instance->getStatus() == STATUS_RUNNING) {
instance->m_connectionHandler->handleConnection(connectionHandle, params /* null params */);
} else {
OATPP_LOGD("[oatpp::network::server::mainLoop()]", "Error. Server already stopped - closing connection...");
}
}
}
instance->setStatus(STATUS_DONE);
}
void Server::run(std::function<bool()> conditional) {
std::unique_lock<std::mutex> ul(m_mutex);
switch (getStatus()) {
case STATUS_STARTING:
throw std::runtime_error("[oatpp::network::server::run()] Error. Server already starting");
case STATUS_RUNNING:
throw std::runtime_error("[oatpp::network::server::run()] Error. Server already started");
}
m_threaded = false;
setStatus(STATUS_CREATED, STATUS_STARTING);
if (conditional) {
m_condition = std::move(conditional);
ul.unlock(); // early unlock
conditionalMainLoop();
} else {
ul.unlock();
mainLoop(this);
}
}
void Server::run(bool startAsNewThread) {
std::unique_lock<std::mutex> ul(m_mutex);
OATPP_LOGW("[oatpp::network::server::run(bool)]", "Using oatpp::network::server::run(bool) is deprecated and will be removed in the next release. Please implement your own threading (See https://github.com/oatpp/oatpp-threaded-starter).")
switch (getStatus()) {
case STATUS_STARTING:
throw std::runtime_error("[oatpp::network::server::run()] Error. Server already starting");
case STATUS_RUNNING:
throw std::runtime_error("[oatpp::network::server::run()] Error. Server already started");
}
m_threaded = startAsNewThread;
setStatus(STATUS_CREATED, STATUS_STARTING);
if (m_threaded) {
m_thread = std::thread(mainLoop, this);
} else {
ul.unlock(); // early unlock
mainLoop(this);
}
}
void Server::stop() {
std::lock_guard<std::mutex> lg(m_mutex);
switch (getStatus()) {
case STATUS_CREATED:
return;
case STATUS_STARTING:
case STATUS_RUNNING:
setStatus(STATUS_STOPPING);
break;
}
if (m_threaded && m_thread.joinable()) {
m_thread.join();
}
}
bool Server::setStatus(v_int32 expectedStatus, v_int32 newStatus) {
v_int32 expected = expectedStatus;
return m_status.compare_exchange_weak(expected, newStatus);
}
void Server::setStatus(v_int32 status) {
m_status.store(status);
}
v_int32 Server::getStatus() {
return m_status.load();
}
Server::~Server() {
stop();
}
}}
| vincent-in-black-sesame/oat | src/oatpp/network/Server.cpp | C++ | apache-2.0 | 5,285 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef oatpp_network_Server_hpp
#define oatpp_network_Server_hpp
#include "oatpp/network/ConnectionHandler.hpp"
#include "oatpp/network/ConnectionProvider.hpp"
#include "oatpp/core/Types.hpp"
#include "oatpp/core/base/Countable.hpp"
#include "oatpp/core/base/Environment.hpp"
#include <atomic>
#include <thread>
#include <functional>
namespace oatpp { namespace network {
/**
* Server calls &id:oatpp::network::ConnectionProvider::get; in the loop and passes obtained Connection
* to &id:oatpp::network::ConnectionHandler;.
*/
class Server : public base::Countable {
private:
static void mainLoop(Server *instance);
void conditionalMainLoop();
bool setStatus(v_int32 expectedStatus, v_int32 newStatus);
void setStatus(v_int32 status);
private:
std::atomic<v_int32> m_status;
std::function<bool()> m_condition;
std::thread m_thread;
std::mutex m_mutex;
std::shared_ptr<ConnectionProvider> m_connectionProvider;
std::shared_ptr<ConnectionHandler> m_connectionHandler;
bool m_threaded;
public:
/**
* Constructor.
* @param connectionProvider - &id:oatpp::network::ConnectionProvider;.
* @param connectionHandler - &id:oatpp::network::ConnectionHandler;.
*/
Server(const std::shared_ptr<ConnectionProvider>& connectionProvider,
const std::shared_ptr<ConnectionHandler>& connectionHandler);
virtual ~Server();
public:
/**
* Status constant.
*/
static const v_int32 STATUS_CREATED;
/**
* Status constant.
*/
static const v_int32 STATUS_STARTING;
/**
* Status constant.
*/
static const v_int32 STATUS_RUNNING;
/**
* Status constant.
*/
static const v_int32 STATUS_STOPPING;
/**
* Status constant.
*/
static const v_int32 STATUS_DONE;
/**
* Create shared Server.
* @param connectionProvider - &id:oatpp::network::ConnectionProvider;.
* @param connectionHandler - &id:oatpp::network::ConnectionHandler;.
* @return - `std::shared_ptr` to Server.
*/
static std::shared_ptr<Server> createShared(const std::shared_ptr<ServerConnectionProvider>& connectionProvider,
const std::shared_ptr<ConnectionHandler>& connectionHandler){
return std::make_shared<Server>(connectionProvider, connectionHandler);
}
/**
* Call &id:oatpp::network::ConnectionProvider::getConnection; in the loop and passes obtained Connection
* to &id:oatpp::network::ConnectionHandler;.
* @param conditional - Function that is called every mainloop iteration to check if the server should continue to run <br>
* Return true to let the server continue, false to shut it down.
*/
void run(std::function<bool()> conditional = nullptr);
/**
* Call &id:oatpp::network::ConnectionProvider::getConnection; in the loop and passes obtained Connection
* to &id:oatpp::network::ConnectionHandler;.
* @param startAsNewThread - Start the server blocking (thread of callee) or non-blocking (own thread)
* @deprecated Deprecated since 1.3.0, will be removed in the next release.
* The new repository https://github.com/oatpp/oatpp-threaded-starter shows many configurations how to run Oat++ in its own thread.
* From simple No-Stop to Stop-Simple and ending in Oat++ completely isolated in its own thread-scope.
* We recommend the Stop-Simple for most applications! You can find it here: https://github.com/oatpp/oatpp-threaded-starter/blob/master/src/App_StopSimple.cpp
* The other examples are non trivial and highly specialized on specific environments or requirements.
* Please read the comments carefully and think about the consequences twice.
* If someone wants to use them please get back to us in an issue in the new repository and we can assist you with them.
* Again: These examples introduce special conditions and requirements for your code!
*/
void run(bool startAsNewThread);
/**
* Break server loop.
* Note: thread can still be blocked on the &l:Server::run (); call as it may be waiting for ConnectionProvider to provide connection.
*/
void stop();
/**
* Get server status.
* @return - one of:<br>
* <ul>
* <li>&l:Server::STATUS_CREATED;</li>
* <li>&l:Server::STATUS_RUNNING;</li>
* <li>&l:Server::STATUS_STOPPING;</li>
* <li>&l:Server::STATUS_DONE;</li>
* </ul>
*/
v_int32 getStatus();
};
}}
#endif /* oatpp_network_Server_hpp */
| vincent-in-black-sesame/oat | src/oatpp/network/Server.hpp | C++ | apache-2.0 | 5,400 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#include "Url.hpp"
#include <cstdlib>
namespace oatpp { namespace network {
oatpp::String Url::Parser::parseScheme(oatpp::parser::Caret& caret) {
v_buff_size pos0 = caret.getPosition();
caret.findChar(':');
v_buff_size size = caret.getPosition() - pos0;
if(size > 0) {
std::unique_ptr<v_char8[]> buff(new v_char8[size]);
std::memcpy(buff.get(), &caret.getData()[pos0], size);
utils::String::lowerCase_ASCII(buff.get(), size);
return oatpp::String((const char*)buff.get(), size);
}
return nullptr;
}
Url::Authority Url::Parser::parseAuthority(oatpp::parser::Caret& caret) {
const char* data = caret.getData();
v_buff_size pos0 = caret.getPosition();
v_buff_size pos = pos0;
v_buff_size hostPos = pos0;
v_buff_size atPos = -1;
v_buff_size portPos = -1;
while (pos < caret.getDataSize()) {
v_char8 a = data[pos];
if(a == '@') {
atPos = pos;
pos ++;
hostPos = pos;
} else if(a == ':') {
pos ++;
portPos = pos; // last ':' in authority proceeds port in case it goes after '@'
} else if(a == '/' || a == '?' || a == '#') {
if(pos == pos0) {
return Url::Authority();
}
break;
} else {
pos ++;
}
}
caret.setPosition(pos);
Url::Authority result;
if(atPos > -1) {
result.userInfo = oatpp::String((const char*)&data[pos0], atPos - pos0);
}
if(portPos > hostPos) {
result.host = oatpp::String((const char*)&data[hostPos], portPos - 1 - hostPos);
char* end;
result.port = std::strtol((const char*)&data[portPos], &end, 10);
bool success = (((v_buff_size)end - (v_buff_size)&data[portPos]) == pos - portPos);
if(!success) {
caret.setError("Invalid port string");
}
} else {
result.host = oatpp::String((const char*)&data[hostPos], pos - pos0);
}
return result;
}
oatpp::String Url::Parser::parsePath(oatpp::parser::Caret& caret) {
auto label = caret.putLabel();
caret.findCharFromSet("?#", 2);
if(label.getSize() > 0) {
return label.toString();
}
return nullptr;
}
void Url::Parser::parseQueryParams(Url::Parameters& params, oatpp::parser::Caret& caret) {
if(caret.findChar('?')) {
do {
caret.inc();
auto nameLabel = caret.putLabel();
v_buff_size charFound = caret.findCharFromSet("=&");
if(charFound == '=') {
nameLabel.end();
caret.inc();
auto valueLabel = caret.putLabel();
caret.findChar('&');
params.put_LockFree(StringKeyLabel(caret.getDataMemoryHandle(), nameLabel.getData(), nameLabel.getSize()),
StringKeyLabel(caret.getDataMemoryHandle(), valueLabel.getData(), valueLabel.getSize()));
} else {
params.put_LockFree(StringKeyLabel(caret.getDataMemoryHandle(), nameLabel.getData(), nameLabel.getSize()), "");
}
} while (caret.canContinueAtChar('&'));
}
}
void Url::Parser::parseQueryParams(Url::Parameters& params, const oatpp::String& str) {
oatpp::parser::Caret caret(str.getPtr());
parseQueryParams(params, caret);
}
Url::Parameters Url::Parser::parseQueryParams(oatpp::parser::Caret& caret) {
Url::Parameters params;
parseQueryParams(params, caret);
return params;
}
Url::Parameters Url::Parser::parseQueryParams(const oatpp::String& str) {
Url::Parameters params;
parseQueryParams(params, str);
return params;
}
Url Url::Parser::parseUrl(oatpp::parser::Caret& caret) {
Url result;
if(caret.findChar(':')) {
caret.setPosition(0);
result.scheme = parseScheme(caret);
caret.canContinueAtChar(':', 1);
} else {
caret.setPosition(0);
}
caret.isAtText("//", 2, true);
if(!caret.isAtChar('/')) {
result.authority = parseAuthority(caret);
}
result.path = parsePath(caret);
result.queryParams = parseQueryParams(caret);
return result;
}
Url Url::Parser::parseUrl(const oatpp::String& str) {
oatpp::parser::Caret caret(str);
return parseUrl(caret);
}
}}
| vincent-in-black-sesame/oat | src/oatpp/network/Url.cpp | C++ | apache-2.0 | 4,973 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef oatpp_network_Url_hpp
#define oatpp_network_Url_hpp
#include "oatpp/core/data/share/LazyStringMap.hpp"
#include "oatpp/core/parser/Caret.hpp"
#include "oatpp/core/Types.hpp"
namespace oatpp { namespace network {
/**
* Class holding URL information.
*/
class Url {
public:
/**
* Convenience typedef for &id:oatpp::data::share::StringKeyLabel;.
*/
typedef oatpp::data::share::StringKeyLabel StringKeyLabel;
public:
/**
* Parameters - map string to string. &id:oatpp::data::share::LazyStringMultimap;.
*/
typedef oatpp::data::share::LazyStringMultimap<oatpp::data::share::StringKeyLabel> Parameters;
public:
/**
* Structure representing URL Authority information.
*/
struct Authority {
/**
* User info.
*/
oatpp::String userInfo;
/**
* Host.
*/
oatpp::String host;
/**
* Port. Treat -1 as undefined or as default.
*/
v_int32 port = -1;
};
public:
/**
* Url parser.
*/
class Parser {
public:
/**
* parse `<scheme>`:
* example "http", "https", "ftp"
* returns lowercase string before ':' char
* caret should be at the first char of the scheme
*/
static oatpp::String parseScheme(oatpp::parser::Caret& caret);
/**
* parse url authority components.
* userinfo is not parsed into login and password separately as
* inclusion of password in userinfo is deprecated and ignored here
* caret should be at the first char of the authority (not at "//")
*/
static Url::Authority parseAuthority(oatpp::parser::Caret& caret);
/**
* parse path of the url
* caret should be at the first char of the path
*/
static oatpp::String parsePath(oatpp::parser::Caret& caret);
/**
* parse query params in form of `"?<paramName>=<paramValue>&<paramName>=<paramValue>..."` referred by ParsingCaret
* and put that params to Parameters map
*/
static void parseQueryParams(Url::Parameters& params, oatpp::parser::Caret& caret);
/**
* parse query params in form of `"?<paramName>=<paramValue>&<paramName>=<paramValue>..."` referred by str
* and put that params to Parameters map
*/
static void parseQueryParams(Url::Parameters& params, const oatpp::String& str);
/**
* parse query params in form of `"?<paramName>=<paramValue>&<paramName>=<paramValue>..."` referred by ParsingCaret
*/
static Url::Parameters parseQueryParams(oatpp::parser::Caret& caret);
/**
* parse query params in form of `"?<paramName>=<paramValue>&<paramName>=<paramValue>..."` referred by str
*/
static Url::Parameters parseQueryParams(const oatpp::String& str);
/**
* Parse Url
* @param caret
* @return parsed URL structure
*/
static Url parseUrl(oatpp::parser::Caret& caret);
/**
* Parse Url
* @param str
* @return parsed URL structure
*/
static Url parseUrl(const oatpp::String& str);
};
public:
/**
* Url scheme. Ex.: [http, https, ftp, etc.]
*/
oatpp::String scheme;
/**
* Utl authority.
*/
Authority authority;
/**
* Path to resource.
*/
oatpp::String path;
/**
* Query params.
*/
Parameters queryParams;
};
}}
#endif /* oatpp_network_url_Url_hpp */
| vincent-in-black-sesame/oat | src/oatpp/network/Url.hpp | C++ | apache-2.0 | 4,335 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#include "ConnectionInactivityChecker.hpp"
namespace oatpp { namespace network { namespace monitor {
ConnectionInactivityChecker::ConnectionInactivityChecker(const std::chrono::duration<v_int64, std::micro>& lastReadTimeout,
const std::chrono::duration<v_int64, std::micro>& lastWriteTimeout)
: m_lastReadTimeout(lastReadTimeout)
, m_lastWriteTimeout(lastWriteTimeout)
{}
std::vector<oatpp::String> ConnectionInactivityChecker::getMetricsList() {
return {};
}
std::shared_ptr<StatCollector> ConnectionInactivityChecker::createStatCollector(const oatpp::String& metricName) {
throw std::runtime_error("[oatpp::network::monitor::ConnectionInactivityChecker::createStatCollector()]: "
"Error. ConnectionInactivityChecker doesn't use any stat collectors.");
}
bool ConnectionInactivityChecker::check(const ConnectionStats& stats, v_int64 currMicroTime) {
return currMicroTime - stats.timestampLastRead < m_lastReadTimeout.count() &&
currMicroTime - stats.timestampLastWrite < m_lastWriteTimeout.count();
}
}}}
| vincent-in-black-sesame/oat | src/oatpp/network/monitor/ConnectionInactivityChecker.cpp | C++ | apache-2.0 | 2,113 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef oatpp_network_monitor_ConnectionInactivityChecker_hpp
#define oatpp_network_monitor_ConnectionInactivityChecker_hpp
#include "MetricsChecker.hpp"
namespace oatpp { namespace network { namespace monitor {
/**
* ConnectionInactivityChecker - checks if a connection is inactive (has no read/writes) and whether it should be closed.
* Extends - &id:oatpp::network::monitor::MetricsChecker;.
*/
class ConnectionInactivityChecker : public MetricsChecker {
private:
std::chrono::duration<v_int64, std::micro> m_lastReadTimeout;
std::chrono::duration<v_int64, std::micro> m_lastWriteTimeout;
public:
/**
* Constructor.
* @param lastReadTimeout - how long can live connection without reads.
* @param lastWriteTimeout - how long can live connection without writes.
*/
ConnectionInactivityChecker(const std::chrono::duration<v_int64, std::micro>& lastReadTimeout,
const std::chrono::duration<v_int64, std::micro>& lastWriteTimeout);
std::vector<oatpp::String> getMetricsList();
std::shared_ptr<StatCollector> createStatCollector(const oatpp::String& metricName);
bool check(const ConnectionStats& stats, v_int64 currMicroTime);
};
}}}
#endif //oatpp_network_monitor_ConnectionInactivityChecker_hpp
| vincent-in-black-sesame/oat | src/oatpp/network/monitor/ConnectionInactivityChecker.hpp | C++ | apache-2.0 | 2,260 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#include "ConnectionMaxAgeChecker.hpp"
namespace oatpp { namespace network { namespace monitor {
ConnectionMaxAgeChecker::ConnectionMaxAgeChecker(const std::chrono::duration<v_int64, std::micro>& maxAge)
: m_maxAge(maxAge)
{}
std::vector<oatpp::String> ConnectionMaxAgeChecker::getMetricsList() {
return {};
}
std::shared_ptr<StatCollector> ConnectionMaxAgeChecker::createStatCollector(const oatpp::String& metricName) {
throw std::runtime_error("[oatpp::network::monitor::ConnectionMaxAgeChecker::createStatCollector()]: "
"Error. ConnectionMaxAgeChecker doesn't use any stat collectors.");
}
bool ConnectionMaxAgeChecker::check(const ConnectionStats& stats, v_int64 currMicroTime) {
return currMicroTime - stats.timestampCreated < m_maxAge.count();
}
}}}
| vincent-in-black-sesame/oat | src/oatpp/network/monitor/ConnectionMaxAgeChecker.cpp | C++ | apache-2.0 | 1,794 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef oatpp_network_monitor_ConnectionMaxAgeChecker_hpp
#define oatpp_network_monitor_ConnectionMaxAgeChecker_hpp
#include "MetricsChecker.hpp"
namespace oatpp { namespace network { namespace monitor {
/**
* ConnectionMaxAgeChecker - checks if connection is too old and should be closed.
* Extends - &id:oatpp::network::monitor::MetricsChecker;.
*/
class ConnectionMaxAgeChecker : public MetricsChecker {
private:
std::chrono::duration<v_int64, std::micro> m_maxAge;
public:
/**
* Constructor.
* @param maxAge - how long should connection live.
*/
ConnectionMaxAgeChecker(const std::chrono::duration<v_int64, std::micro>& maxAge);
std::vector<oatpp::String> getMetricsList();
std::shared_ptr<StatCollector> createStatCollector(const oatpp::String& metricName);
bool check(const ConnectionStats& stats, v_int64 currMicroTime);
};
}}}
#endif //oatpp_network_monitor_ConnectionMaxAgeChecker_hpp
| vincent-in-black-sesame/oat | src/oatpp/network/monitor/ConnectionMaxAgeChecker.hpp | C++ | apache-2.0 | 1,924 |