OpenLCP/acn/pdu-stream.h

99 lines
2.8 KiB
C++

/*
pdu-stream.h
Copyright (c) 2021 Kevin Matz (kevin.matz@gmail.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#pragma once
#include <memory>
#include <iostream>
namespace ACN {
namespace PDU {
/**
* @brief Input/Output stream of nested PDU
*/
class pdu_stream
: private std::basic_streambuf<uint8_t>
, public std::basic_iostream<uint8_t>
{
public:
pdu_stream(uint8_t * p, std::streamsize l);
// input sequence
uint32_t available() { return in_avail(); }
uint8_t * data() { return gptr(); }
pdu_stream& operator>> (uint8_t& val);
pdu_stream& operator>> (uint16_t& val);
pdu_stream& operator>> (uint32_t& val);
pdu_stream& operator>> (uint64_t& val);
template<typename T> T readType()
{
if (in_avail() < sizeof(T))
setstate(std::ios_base::failbit);
if (fail())
return 0;
T ret = 0;
auto data = reinterpret_cast<uint8_t*>(&ret);
for (int i = sizeof(T); --i >= 0; )
data[i] = get();
if (!in_avail())
setstate(std::ios_base::eofbit);
return ret;
}
// output sequence
uint32_t size() { return pptr() - pbase(); }
uint8_t * base() { return pbase(); }
pdu_stream& operator<< (const uint8_t& val);
pdu_stream& operator<< (const uint16_t& val);
pdu_stream& operator<< (const uint32_t& val);
pdu_stream& operator<< (const uint64_t& val);
template<typename T> void writeType (const T& val)
{
auto data = reinterpret_cast<const uint8_t*>(&val);
for (int i = sizeof(T); --i >= 0; )
put(data[i]);
}
};
using Stream = std::shared_ptr<pdu_stream>;
/**
* @brief The pdu_stream_object struct
*/
struct pdu_stream_object
{
virtual ~pdu_stream_object() {};
virtual size_t streamSize() const = 0;
virtual void iStream(Stream) = 0;
virtual void oStream(Stream) const = 0;
};
} // PDU
} // ACN