parent
68e54805af
commit
b16d7c6a87
@ -0,0 +1,33 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
template<typename T>
|
||||||
|
struct Slice {
|
||||||
|
virtual const void* area() const =0;
|
||||||
|
virtual void* area() = 0;
|
||||||
|
virtual size_t size() const = 0;
|
||||||
|
|
||||||
|
inline T* ptr() { return (T*)area(); }
|
||||||
|
inline const T* ptr() const { return (const T*)area(); }
|
||||||
|
|
||||||
|
inline size_t size_bytes() const { return size() * sizeof(T); }
|
||||||
|
|
||||||
|
inline unsigned char* as_bytes() { return (unsigned char*)area(); }
|
||||||
|
inline const unsigned char* as_bytes() const { return (const unsigned char*)area(); }
|
||||||
|
|
||||||
|
inline T& operator[](size_t index) {
|
||||||
|
if(index >= size()) throw "Size too large";
|
||||||
|
return ptr()[index];
|
||||||
|
}
|
||||||
|
inline const T& operator[](size_t index) const {
|
||||||
|
if(index >= size()) throw "Size too large";
|
||||||
|
return ptr()[index];
|
||||||
|
}
|
||||||
|
|
||||||
|
template<typename U>
|
||||||
|
inline U* area_as() requires(sizeof(T) % sizeof(U) == 0) { return (U*)area(); }
|
||||||
|
template<typename U>
|
||||||
|
inline const U* area_as() const requires(sizeof(T) % sizeof(U) == 0) { return (U*)area(); }
|
||||||
|
|
||||||
|
template<typename U>
|
||||||
|
size_t size_as() const requires(sizeof(T) % sizeof(U) == 0) { return size_bytes() / sizeof(U); }
|
||||||
|
};
|
@ -1,18 +1,34 @@
|
|||||||
#include <cow.hpp>
|
#include <cow.hpp>
|
||||||
|
|
||||||
#include <cstdio>
|
#include <cstdio>
|
||||||
|
#include <cstring>
|
||||||
|
|
||||||
|
void write_fake(Cow& clone, const char* string)
|
||||||
|
{
|
||||||
|
strncpy(clone.area_as<char>(), string, clone.size_as<char>()-1);
|
||||||
|
}
|
||||||
|
|
||||||
|
void read_fake(const Cow& clone)
|
||||||
|
{
|
||||||
|
printf("read_fake: %s\n", clone.area_as<char>());
|
||||||
|
}
|
||||||
|
|
||||||
int main()
|
int main()
|
||||||
{
|
{
|
||||||
Cow real(4096);
|
Cow real(4096);
|
||||||
|
|
||||||
|
write_fake(real, "Hello world");
|
||||||
|
read_fake(real);
|
||||||
|
|
||||||
|
Cow::Fake clone = real;
|
||||||
|
printf("Fake size: %lu\n", clone.size());
|
||||||
|
printf("Fake ptr: %p\n", clone.area());
|
||||||
|
|
||||||
printf("Fast size: %lu, slow size: %lu\n", real.size_unsafe(), real.size());
|
read_fake(clone);
|
||||||
|
write_fake(clone, "hello fake!");
|
||||||
|
read_fake(clone);
|
||||||
|
read_fake(real);
|
||||||
|
|
||||||
Cow::Fake clone = real;
|
printf("First byte of: real = %x, fake = %x\n", real[0], clone[0]);
|
||||||
{
|
|
||||||
Cow::Fake clone2 = clone;
|
|
||||||
}
|
|
||||||
if(0) cow_size_unsafe(NULL);
|
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in new issue