2018-12-19 22:57:56 +01:00
|
|
|
//
|
2018-12-31 23:02:34 +01:00
|
|
|
// Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2019
|
2018-12-19 22:57:56 +01:00
|
|
|
//
|
|
|
|
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
|
|
|
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
|
|
|
//
|
|
|
|
#pragma once
|
|
|
|
|
|
|
|
#include <cstring>
|
|
|
|
|
|
|
|
namespace td {
|
|
|
|
|
2018-12-19 23:46:55 +01:00
|
|
|
namespace detail {
|
|
|
|
|
2018-12-19 22:57:56 +01:00
|
|
|
template <class T>
|
|
|
|
class As {
|
|
|
|
public:
|
2018-12-19 23:46:55 +01:00
|
|
|
explicit As(void *ptr) : ptr_(ptr) {
|
2018-12-19 22:57:56 +01:00
|
|
|
}
|
2018-12-19 23:46:55 +01:00
|
|
|
|
|
|
|
As(const As &new_value) = delete;
|
|
|
|
As &operator=(const As &) = delete;
|
2018-12-19 22:57:56 +01:00
|
|
|
As(As &&) = default;
|
2018-12-19 23:46:55 +01:00
|
|
|
As &operator=(As &&new_value) && {
|
|
|
|
std::memcpy(ptr_, new_value.ptr_, sizeof(T));
|
2018-12-19 22:57:56 +01:00
|
|
|
return *this;
|
|
|
|
}
|
2018-12-19 23:46:55 +01:00
|
|
|
~As() = default;
|
|
|
|
|
|
|
|
As &operator=(const T &new_value) && {
|
|
|
|
std::memcpy(ptr_, &new_value, sizeof(T));
|
2018-12-19 22:57:56 +01:00
|
|
|
return *this;
|
|
|
|
}
|
|
|
|
|
|
|
|
operator T() const {
|
|
|
|
T res;
|
2018-12-19 23:46:55 +01:00
|
|
|
std::memcpy(&res, ptr_, sizeof(T));
|
2018-12-19 22:57:56 +01:00
|
|
|
return res;
|
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
|
|
|
void *ptr_;
|
|
|
|
};
|
|
|
|
|
|
|
|
template <class T>
|
|
|
|
class ConstAs {
|
|
|
|
public:
|
2018-12-19 23:46:55 +01:00
|
|
|
explicit ConstAs(const void *ptr) : ptr_(ptr) {
|
2018-12-19 22:57:56 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
operator T() const {
|
|
|
|
T res;
|
2018-12-19 23:46:55 +01:00
|
|
|
std::memcpy(&res, ptr_, sizeof(T));
|
2018-12-19 22:57:56 +01:00
|
|
|
return res;
|
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
|
|
|
const void *ptr_;
|
|
|
|
};
|
|
|
|
|
2018-12-19 23:46:55 +01:00
|
|
|
} // namespace detail
|
|
|
|
|
2018-12-19 22:57:56 +01:00
|
|
|
template <class ToT, class FromT>
|
2018-12-19 23:46:55 +01:00
|
|
|
detail::As<ToT> as(FromT *from) {
|
|
|
|
return detail::As<ToT>(from);
|
2018-12-19 22:57:56 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
template <class ToT, class FromT>
|
2018-12-19 23:46:55 +01:00
|
|
|
const detail::ConstAs<ToT> as(const FromT *from) {
|
|
|
|
return detail::ConstAs<ToT>(from);
|
2018-12-19 22:57:56 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
} // namespace td
|