basic slicing reinterpretation

cpp
Avril 4 years ago
parent 4432e50ebc
commit 46fad4fd2c
Signed by: flanchan
GPG Key ID: 284488987C31F630

@ -45,6 +45,11 @@ struct Span {
inline Slice slice(size_t start, size_t len) { if(bounds_ok(start,len)) return Slice(ptr()+start, len); else throw "Out of bounds slice"; } inline Slice slice(size_t start, size_t len) { if(bounds_ok(start,len)) return Slice(ptr()+start, len); else throw "Out of bounds slice"; }
inline Slice slice(size_t start) { return slice(start, size()-start); } inline Slice slice(size_t start) { return slice(start, size()-start); }
inline Slice slice() { return slice(0, size()); }
template<typename U>
inline Span<U>::Slice reinterpret() { return typename Span<U>::Slice((U*)area(), size_bytes() / sizeof(U)); }
template<typename U>
inline Span<const U>::Slice reinterpret() const { return typename Span<const U>::Slice((const U*)area(), size_bytes() / sizeof(U)); }
}; };
/// A slice of memory with a backing pointer and size. /// A slice of memory with a backing pointer and size.
@ -59,6 +64,7 @@ struct Span<T>::Slice : public Span<T> {
inline const void* area() const override { return _area; } inline const void* area() const override { return _area; }
inline void* area() override { return _area; } inline void* area() override { return _area; }
inline size_t size() const override { return _size; } inline size_t size() const override { return _size; }
private: private:
void* const _area; void* const _area;

@ -3,9 +3,11 @@
#include <cstdio> #include <cstdio>
#include <cstring> #include <cstring>
void print_slice(Slice<unsigned char> memory) template<typename T = unsigned char>
void print_slice(Slice<T> memory)
{ {
printf("slice: { %p, %lu }\n", memory.area(), memory.size()); printf("slice: { %p, %lu (%lu bytes) }\n", memory.area(), memory.size(), memory.size_bytes());
} }
void write_fake(Cow& clone, const char* string) void write_fake(Cow& clone, const char* string)
@ -23,7 +25,7 @@ int main()
Cow real(4096); Cow real(4096);
printf("Created real: "); printf("Created real: ");
print_slice(real); print_slice(real);
write_fake(real, "Hello world"); write_fake(real, "Hello world");
read_fake(real); read_fake(real);

Loading…
Cancel
Save