/** * @file bin.cpp * @author myusgun@gmail.com * @brief bin */ #include "cf/bin.h" #include #include cf::bin::bin(const cf::uint8_t * in, const cf::size_t length) { set(in, length); } cf::bin::bin(const cf::char_t * in) { if (!in) return; set(reinterpret_cast(in), strlen(reinterpret_cast(in))); } cf::bin::bin(const bin & in) : mBin(in.mBin) { } cf::void_t cf::bin::clear() { mBin.clear(); } cf::uint8_t * cf::bin::buffer() const { return const_cast(&mBin[0]); } cf::size_t cf::bin::size() const { return mBin.size(); } cf::bool_t cf::bin::empty() const { return mBin.empty(); } cf::void_t cf::bin::resize(const cf::size_t size) { mBin.resize(size); } cf::void_t cf::bin::set(const cf::uint8_t * in, const cf::size_t length) { if (!in) return; resize(length); memcpy(buffer(), in, length); } cf::void_t cf::bin::append(const cf::uint8_t * in, const cf::size_t appendedSize) { const cf::size_t position = size(); resize(size() + appendedSize); memcpy(&buffer()[position], in, appendedSize); } cf::void_t cf::bin::append(const cf::bin & in) { append(in.buffer(), in.size()); } cf::bool_t cf::bin::equal(const cf::bin & in) const { if (size() != in.size()) return false; if (size() > 0) { if (memcmp(buffer(), in.buffer(), size())) return false; } return true; } cf::bin & cf::bin::operator =(const cf::bin & in) { mBin = in.mBin; return *this; } cf::void_t cf::bin::operator +=(const cf::bin & in) { append(in); } cf::bin cf::bin::operator +(const cf::bin & in) const { bin out(in); out.append(in); return out; } cf::bool_t cf::bin::operator ==(const cf::bin & in) const { return equal(in); } cf::bool_t cf::bin::operator !=(const cf::bin & in) const { return !equal(in); } cf::size_t cf::bin::find(const cf::uint8_t * in, const cf::size_t length) const { cf::size_t limit = size() - length; if (limit < 0 || !in) return -1; for (cf::size_t iter = 0 ; iter <= limit ; iter++) { if (!memcmp(buffer() + iter, in, length)) return iter; } return -1; } cf::void_t cf::bin::print(const cf::char_t * prefix, const cf::size_t limit, FILE * fp) const { cf::size_t i, j; cf::size_t realsize = size() < limit ? size() : limit; fprintf(fp, "[bin][%s] %lu bytes\n", prefix, size()); for (i = 0 ; i < realsize ; i += 16) { fprintf(fp, "%06lx : ", (cf::size_t)i); for (j = 0; j < 16; j++) { if (i + j < realsize) fprintf(fp, "%02x ", buffer()[i + j]); else fprintf(fp, " "); } fprintf(fp, " "); for (j = 0 ; j < 16 ; j++) { #define IS_READABLE_CHAR(__c) (' ' <= __c && __c <= '~') if (i+j < realsize) fprintf(fp, "%c", IS_READABLE_CHAR(buffer()[i + j]) ? buffer()[i + j] : '.'); } fprintf(fp, "\n"); } }