1
0
mirror of https://github.com/VCMP-SqMod/SqMod.git synced 2025-06-15 22:57:12 +02:00

Update the module API and merge shared code between modules and host plugin.

This commit is contained in:
Sandu Liviu Catalin
2016-06-03 21:26:19 +03:00
parent 423bdfcdab
commit 0c92601362
56 changed files with 2781 additions and 2688 deletions

View File

@ -457,11 +457,11 @@ void Register_AABB(HSQUIRRELVM vm)
.Var(_SC("Max"), &AABB::max)
// Properties
.Prop(_SC("Abs"), &AABB::Abs)
// Core Metamethods
// Core Meta-methods
.Func(_SC("_tostring"), &AABB::ToString)
.SquirrelFunc(_SC("_typename"), &AABB::Typename)
.Func(_SC("_cmp"), &AABB::Cmp)
// Metamethods
// Meta-methods
.Func< AABB (AABB::*)(const AABB &) const >(_SC("_add"), &AABB::operator +)
.Func< AABB (AABB::*)(const AABB &) const >(_SC("_sub"), &AABB::operator -)
.Func< AABB (AABB::*)(const AABB &) const >(_SC("_mul"), &AABB::operator *)

View File

@ -1,611 +0,0 @@
// ------------------------------------------------------------------------------------------------
#include "Base/Buffer.hpp"
// ------------------------------------------------------------------------------------------------
#include <cstdlib>
#include <cstring>
#include <exception>
#include <stdexcept>
// ------------------------------------------------------------------------------------------------
namespace SqMod {
/* ------------------------------------------------------------------------------------------------
* Compute the next power of two for the specified number.
*/
inline unsigned int NextPow2(unsigned int num)
{
--num;
num |= num >> 1;
num |= num >> 2;
num |= num >> 4;
num |= num >> 8;
num |= num >> 16;
return ++num;
}
/* ------------------------------------------------------------------------------------------------
* Throw an memory exception.
*/
void ThrowMemExcept(const char * msg, ...)
{
// Exception messages should be concise
char buffer[128];
// Variable arguments structure
va_list args;
// Get the specified arguments
va_start(args, msg);
// Run the specified format
int ret = std::vsnprintf(buffer, sizeof(buffer), msg, args);
// Check for formatting errors
if (ret < 0)
{
throw std::runtime_error("Unknown memory error");
}
// Throw the actual exception
throw std::runtime_error(buffer);
}
/* ------------------------------------------------------------------------------------------------
* Allocate a memory buffer and return it.
*/
static Buffer::Pointer AllocMem(Buffer::SzType size)
{
// Attempt to allocate memory directly
Buffer::Pointer ptr = reinterpret_cast< Buffer::Pointer >(std::malloc(size));
// Validate the allocated memory
if (!ptr)
{
ThrowMemExcept("Unable to allocate (%u) bytes of memory", size);
}
// Return the allocated memory
return ptr;
}
/* ------------------------------------------------------------------------------------------------
* ...
*/
class MemCat
{
// --------------------------------------------------------------------------------------------
friend class Memory;
friend class Buffer;
public:
// --------------------------------------------------------------------------------------------
typedef Buffer::Value Value; // The type of value used to represent a byte.
// --------------------------------------------------------------------------------------------
typedef Buffer::Reference Reference; // A reference to the stored value type.
typedef Buffer::ConstRef ConstRef; // A const reference to the stored value type.
// --------------------------------------------------------------------------------------------
typedef Buffer::Pointer Pointer; // A pointer to the stored value type.
typedef Buffer::ConstPtr ConstPtr; // A const pointer to the stored value type.
// --------------------------------------------------------------------------------------------
typedef Buffer::SzType SzType; // The type used to represent size in general.
private:
/* --------------------------------------------------------------------------------------------
* Structure used to store a memory chunk in the linked list.
*/
struct Node
{
// ----------------------------------------------------------------------------------------
SzType mCap; // The size of the memory chunk.
Pointer mPtr; // Pointer to the memory chunk.
Node* mNext; // The next node in the list.
/* ----------------------------------------------------------------------------------------
* Base constructor.
*/
Node(Node * next)
: mCap(0)
, mPtr(nullptr)
, mNext(next)
{
/* ... */
}
};
// --------------------------------------------------------------------------------------------
static Node * s_Nodes; /* List of unused node instances. */
// --------------------------------------------------------------------------------------------
Node* m_Head; /* The head memory node. */
/* --------------------------------------------------------------------------------------------
* Default constructor.
*/
MemCat()
: m_Head(nullptr)
{
/* ... */
}
/* --------------------------------------------------------------------------------------------
* Destructor.
*/
~MemCat()
{
for (Node * node = m_Head, * next = nullptr; node; node = next)
{
// Free the memory (if any)
if (node->mPtr)
{
std::free(node->mPtr);
}
// Save the next node
next = node->mNext;
// Release the node instance
delete node;
}
// Explicitly set the head node to null
m_Head = nullptr;
}
/* --------------------------------------------------------------------------------------------
* Clear all memory buffers from the pool.
*/
void Clear()
{
for (Node * node = m_Head, * next = nullptr; node; node = next)
{
// Free the memory (if any)
if (node->mPtr)
{
free(node->mPtr);
}
// Save the next node
next = node->mNext;
// Release the node instance
Push(node);
}
// Explicitly set the head node to null
m_Head = nullptr;
}
/* --------------------------------------------------------------------------------------------
* Grab a memory buffer from the pool.
*/
void Grab(Pointer & ptr, SzType & size)
{
// NOTE: Function assumes (size > 0)
// Find a buffer large enough to satisfy the requested size
for (Node * node = m_Head, * prev = nullptr; node; prev = node, node = node->mNext)
{
// Is this buffer large enough?
if (node->mCap >= size)
{
// Was there a previous node?
if (prev)
{
prev->mNext = node->mNext;
}
// Probably this was the head
else
{
m_Head = node->mNext;
}
// Assign the memory
ptr = node->mPtr;
// Assign the size
size = node->mCap;
// Release the node instance
Push(node);
// Exit the function
return;
}
}
// Round up the size to a power of two number
size = (size & (size - 1)) ? NextPow2(size) : size;
// Allocate the memory directly
ptr = AllocMem(size);
// See if the memory could be allocated
// (shouldn't reach this point if allocation failed)
if (!ptr)
{
// Revert the size
size = 0;
// Throw the exception
ThrowMemExcept("Unable to allocate (%u) bytes of memory", size);
}
}
/* --------------------------------------------------------------------------------------------
* Return a memory buffer to the pool.
*/
void Drop(Pointer & ptr, SzType & size)
{
if (!ptr)
{
ThrowMemExcept("Cannot store invalid memory buffer");
}
// Request a node instance
Node * node = Pull();
// Assign the specified memory
node->mPtr = ptr;
// Assign the specified size
node->mCap = size;
// Demote the current head node
node->mNext = m_Head;
// Promote as the head node
m_Head = node;
}
/* --------------------------------------------------------------------------------------------
* Allocate a group of nodes and pool them for later use.
*/
static void Make()
{
for (SzType n = 16; n; --n)
{
// Create a new node instance
s_Nodes = new Node(s_Nodes);
// Validate the head node
if (!s_Nodes)
{
ThrowMemExcept("Unable to allocate memory nodes");
}
}
}
/* --------------------------------------------------------------------------------------------
* Retrieve an unused node from the free list.
*/
static Node * Pull()
{
// Are there any nodes available?
if (!s_Nodes)
{
Make(); // Make some!
}
// Grab the head node
Node * node = s_Nodes;
// Promote the next node as the head
s_Nodes = node->mNext;
// Return the node
return node;
}
/* --------------------------------------------------------------------------------------------
* Return a node to the free list.
*/
static void Push(Node * node)
{
// See if the node is even valid
if (!node)
{
ThrowMemExcept("Attempting to push invalid node");
}
// Demote the current head node
node->mNext = s_Nodes;
// Promote as the head node
s_Nodes = node;
}
};
// ------------------------------------------------------------------------------------------------
MemCat::Node * MemCat::s_Nodes = nullptr;
/* ------------------------------------------------------------------------------------------------
* Lightweight memory allocator to reduce the overhead of small allocations.
*/
class Memory
{
// --------------------------------------------------------------------------------------------
friend class Buffer; // Allow the buffer type to access the memory categories.
friend class MemRef; // Allow the memory manager reference to create new instances.
private:
/* --------------------------------------------------------------------------------------------
* Default constructor.
*/
Memory()
: m_Small()
, m_Medium()
, m_Large()
{
// Allocate several nodes for when memory starts pooling
MemCat::Make();
}
/* --------------------------------------------------------------------------------------------
* Destructor.
*/
~Memory()
{
for (MemCat::Node * node = MemCat::s_Nodes, * next = nullptr; node; node = next)
{
// Save the next node
next = node->mNext;
// Release the node instance
delete node;
}
// Explicitly set the head node to null
MemCat::s_Nodes = nullptr;
}
private:
// --------------------------------------------------------------------------------------------
MemCat m_Small; // Small memory allocations of <= 1024 bytes.
MemCat m_Medium; // Medium memory allocations of <= 4096 bytes.
MemCat m_Large; // Large memory allocations of <= 4096 bytes.
};
// ------------------------------------------------------------------------------------------------
MemRef MemRef::s_Mem;
// ------------------------------------------------------------------------------------------------
void MemRef::Grab()
{
if (m_Ptr)
{
++(*m_Ref);
}
}
// ------------------------------------------------------------------------------------------------
void MemRef::Drop()
{
if (m_Ptr && --(*m_Ref) == 0)
{
delete m_Ptr;
delete m_Ref;
m_Ptr = nullptr;
m_Ref = nullptr;
}
}
// ------------------------------------------------------------------------------------------------
const MemRef & MemRef::Get()
{
if (!s_Mem.m_Ptr)
{
s_Mem.m_Ptr = new Memory();
s_Mem.m_Ref = new Counter(1);
}
return s_Mem;
}
// ------------------------------------------------------------------------------------------------
Buffer::Buffer(const Buffer & o)
: m_Ptr(nullptr)
, m_Cap(o.m_Cap)
, m_Cur(o.m_Cur)
, m_Mem(o.m_Mem)
{
if (m_Cap)
{
Request(o.m_Cap);
std::memcpy(m_Ptr, o.m_Ptr, o.m_Cap);
}
}
// ------------------------------------------------------------------------------------------------
Buffer::~Buffer()
{
// Do we have a buffer?
if (m_Ptr)
{
Release(); // Release it!
}
}
// ------------------------------------------------------------------------------------------------
Buffer & Buffer::operator = (const Buffer & o)
{
if (m_Ptr != o.m_Ptr)
{
// Can we work in the current buffer?
if (m_Cap && o.m_Cap <= m_Cap)
{
// It's safe to copy the data
std::memcpy(m_Ptr, o.m_Ptr, o.m_Cap);
}
// Do we even have data to copy?
else if (!o.m_Cap)
{
// Do we have a buffer?
if (m_Ptr)
{
Release(); // Release it!
}
}
else
{
// Do we have a buffer?
if (m_Ptr)
{
Release(); // Release it!
}
// Request a larger buffer
Request(o.m_Cap);
// Now it's safe to copy the data
std::memcpy(m_Ptr, o.m_Ptr, o.m_Cap);
}
// Also copy the edit cursor
m_Cur = o.m_Cur;
}
return *this;
}
// ------------------------------------------------------------------------------------------------
void Buffer::Grow(SzType n)
{
// Backup the current memory
Buffer bkp(m_Ptr, m_Cap, m_Cur, m_Mem);
// Acquire a bigger buffer
Request(bkp.m_Cap + n);
// Copy the data from the old buffer
std::memcpy(m_Ptr, bkp.m_Ptr, bkp.m_Cap);
// Copy the previous edit cursor
m_Cur = bkp.m_Cur;
}
// ------------------------------------------------------------------------------------------------
void Buffer::Request(SzType n)
{
// NOTE: Function assumes (n > 0)
// Is there a memory manager available?
if (!m_Mem)
{
// Round up the size to a power of two number
n = (n & (n - 1)) ? NextPow2(n) : n;
// Allocate the memory directly
m_Ptr = AllocMem(n);
}
// Find out in which category does this buffer reside
else if (n <= 1024)
{
m_Mem->m_Small.Grab(m_Ptr, n);
}
else if (n <= 4096)
{
m_Mem->m_Medium.Grab(m_Ptr, n);
}
else
{
m_Mem->m_Large.Grab(m_Ptr, n);
}
// If no errors occurred then we can set the size
m_Cap = n;
}
// ------------------------------------------------------------------------------------------------
void Buffer::Release()
{
// TODO: Implement a limit on how much memory can actually be pooled.
// Is there a memory manager available?
if (!m_Mem)
{
std::free(m_Ptr); // Deallocate the memory directly
}
// Find out to which category does this buffer belong
else if (m_Cap <= 1024)
{
m_Mem->m_Small.Drop(m_Ptr, m_Cap);
}
else if (m_Cap <= 4096)
{
m_Mem->m_Medium.Drop(m_Ptr, m_Cap);
}
else
{
m_Mem->m_Large.Drop(m_Ptr, m_Cap);
}
// Explicitly reset the buffer
m_Ptr = nullptr;
m_Cap = 0;
m_Cur = 0;
}
// ------------------------------------------------------------------------------------------------
Buffer::SzType Buffer::Write(SzType pos, ConstPtr data, SzType size)
{
// Do we have what to write?
if (!data || !size)
{
return 0;
}
// See if the buffer size must be adjusted
else if ((pos + size) >= m_Cap)
{
// Acquire a larger buffer
Grow((pos + size) - m_Cap + 32);
}
// Copy the data into the internal buffer
std::memcpy(m_Ptr + pos, data, size);
// Return the amount of data written to the buffer
return size;
}
// ------------------------------------------------------------------------------------------------
Buffer::SzType Buffer::WriteF(SzType pos, const char * fmt, ...)
{
// Initialize the variable argument list
va_list args;
va_start(args, fmt);
// Call the function that takes the variable argument list
const SzType ret = WriteF(pos, fmt, args);
// Finalize the variable argument list
va_end(args);
// Return the result
return ret;
}
// ------------------------------------------------------------------------------------------------
Buffer::SzType Buffer::WriteF(SzType pos, const char * fmt, va_list args)
{
// Is the specified position within range?
if (pos >= m_Cap)
{
// Acquire a larger buffer
Grow(pos - m_Cap + 32);
}
// Backup the variable argument list
va_list args_cpy;
va_copy(args_cpy, args);
// Attempt to write to the current buffer
// (if empty, it should tell us the necessary size)
int ret = std::vsnprintf(m_Ptr + pos, m_Cap, fmt, args);
// Do we need a bigger buffer?
if ((pos + ret) >= m_Cap)
{
// Acquire a larger buffer
Grow((pos + ret) - m_Cap + 32);
// Retry writing the requested information
ret = std::vsnprintf(m_Ptr + pos, m_Cap, fmt, args_cpy);
}
// Return the value 0 if data could not be written
if (ret < 0)
{
return 0;
}
// Return the number of written characters
return static_cast< SzType >(ret);
}
// ------------------------------------------------------------------------------------------------
Buffer::SzType Buffer::WriteS(SzType pos, ConstPtr str)
{
// Is there any string to write?
if (str && *str != '\0')
{
// Forward this to the regular write function
return Write(pos, str, std::strlen(str));
}
// Nothing to write
return 0;
}
// ------------------------------------------------------------------------------------------------
void Buffer::AppendF(const char * fmt, ...)
{
// Initialize the variable argument list
va_list args;
va_start(args, fmt);
// Forward this to the regular write function
m_Cur += WriteF(m_Cur, fmt, args);
// Finalize the variable argument list
va_end(args);
}
// ------------------------------------------------------------------------------------------------
void Buffer::AppendS(const char * str)
{
// Is there any string to write?
if (str)
{
m_Cur += Write(m_Cur, str, std::strlen(str));
}
}
} // Namespace:: SqMod

View File

@ -1,833 +0,0 @@
#ifndef _BASE_BUFFER_HPP_
#define _BASE_BUFFER_HPP_
// ------------------------------------------------------------------------------------------------
#include <cassert>
#include <cstdarg>
// ------------------------------------------------------------------------------------------------
#include <utility>
// ------------------------------------------------------------------------------------------------
namespace SqMod {
// ------------------------------------------------------------------------------------------------
class Memory;
class Buffer;
/* ------------------------------------------------------------------------------------------------
* A counted reference to a memory manager instance.
*/
class MemRef
{
private:
// --------------------------------------------------------------------------------------------
static MemRef s_Mem;
// --------------------------------------------------------------------------------------------
typedef unsigned int Counter;
// --------------------------------------------------------------------------------------------
Memory* m_Ptr; /* The memory manager instance. */
Counter* m_Ref; /* Reference count to the managed instance. */
/* --------------------------------------------------------------------------------------------
* Grab a strong reference to a memory manager.
*/
void Grab();
/* --------------------------------------------------------------------------------------------
* Drop a strong reference to a memory manager.
*/
void Drop();
public:
/* --------------------------------------------------------------------------------------------
* Get a reference to the global memory manager instance.
*/
static const MemRef & Get();
/* --------------------------------------------------------------------------------------------
* Default constructor (null).
*/
MemRef()
: m_Ptr(s_Mem.m_Ptr)
, m_Ref(s_Mem.m_Ref)
{
Grab();
}
/* --------------------------------------------------------------------------------------------
* Copy constructor.
*/
MemRef(const MemRef & o)
: m_Ptr(o.m_Ptr)
, m_Ref(o.m_Ref)
{
Grab();
}
/* --------------------------------------------------------------------------------------------
* Move constructor.
*/
MemRef(MemRef && o)
: m_Ptr(o.m_Ptr), m_Ref(o.m_Ref)
{
o.m_Ptr = nullptr;
o.m_Ref = nullptr;
}
/* --------------------------------------------------------------------------------------------
* Destructor.
*/
~MemRef()
{
Drop();
}
/* --------------------------------------------------------------------------------------------
* Copy assignment operator.
*/
MemRef & operator = (const MemRef & o)
{
if (m_Ptr != o.m_Ptr)
{
Drop();
m_Ptr = o.m_Ptr;
m_Ref = o.m_Ref;
Grab();
}
return *this;
}
/* --------------------------------------------------------------------------------------------
* Move assignment operator.
*/
MemRef & operator = (MemRef && o)
{
if (m_Ptr != o.m_Ptr)
{
Drop();
m_Ptr = o.m_Ptr;
m_Ref = o.m_Ref;
o.m_Ptr = nullptr;
o.m_Ref = nullptr;
}
return *this;
}
/* --------------------------------------------------------------------------------------------
* Perform an equality comparison between two memory managers.
*/
bool operator == (const MemRef & o) const
{
return (m_Ptr == o.m_Ptr);
}
/* --------------------------------------------------------------------------------------------
* Perform an inequality comparison between two memory managers.
*/
bool operator != (const MemRef & o) const
{
return (m_Ptr != o.m_Ptr);
}
/* --------------------------------------------------------------------------------------------
* Implicit conversion to boolean for use in boolean operations.
*/
operator bool () const
{
return m_Ptr;
}
/* --------------------------------------------------------------------------------------------
* Member operator for dereferencing the managed pointer.
*/
Memory * operator -> () const
{
assert(m_Ptr);
return m_Ptr;
}
/* --------------------------------------------------------------------------------------------
* Indirection operator for obtaining a reference of the managed pointer.
*/
Memory & operator * () const
{
assert(m_Ptr);
return *m_Ptr;
}
/* --------------------------------------------------------------------------------------------
* Release the reference to the managed instance.
*/
void Reset()
{
if (m_Ptr)
{
Drop();
}
}
};
// ------------------------------------------------------------------------------------------------
void ThrowMemExcept(const char * msg, ...);
/* ------------------------------------------------------------------------------------------------
* Reusable and re-scalable buffer memory for quick memory allocations.
*/
class Buffer
{
public:
// --------------------------------------------------------------------------------------------
typedef char Value; // The type of value used to represent a byte.
// --------------------------------------------------------------------------------------------
typedef Value & Reference; // A reference to the stored value type.
typedef const Value & ConstRef; // A const reference to the stored value type.
// --------------------------------------------------------------------------------------------
typedef Value * Pointer; // A pointer to the stored value type.
typedef const Value * ConstPtr; // A const pointer to the stored value type.
// --------------------------------------------------------------------------------------------
typedef unsigned int SzType; // The type used to represent size in general.
private:
/* --------------------------------------------------------------------------------------------
* Construct and take ownership of the specified buffer.
*/
Buffer(Pointer & ptr, SzType & cap, SzType & cur, const MemRef & mem)
: m_Ptr(ptr)
, m_Cap(cap)
, m_Cur(cur)
, m_Mem(mem)
{
ptr = nullptr;
cap = 0;
cur = 0;
}
public:
/* --------------------------------------------------------------------------------------------
* Default constructor. (null)
*/
Buffer()
: m_Ptr(nullptr)
, m_Cap(0)
, m_Cur(0)
, m_Mem(MemRef::Get())
{
/* ... */
}
/* --------------------------------------------------------------------------------------------
* Explicit size constructor.
*/
Buffer(SzType n)
: m_Ptr(nullptr)
, m_Cap(0)
, m_Cur(0)
, m_Mem(MemRef::Get())
{
Request(n < 8 ? 8 : n);
}
/* --------------------------------------------------------------------------------------------
* Copy constructor.
*/
Buffer(const Buffer & o);
/* --------------------------------------------------------------------------------------------
* Move constructor.
*/
Buffer(Buffer && o)
: m_Ptr(o.m_Ptr)
, m_Cap(o.m_Cap)
, m_Cur(o.m_Cur)
, m_Mem(o.m_Mem)
{
o.m_Ptr = nullptr;
}
/* --------------------------------------------------------------------------------------------
* Destructor.
*/
~Buffer();
/* --------------------------------------------------------------------------------------------
* Copy assignment operator.
*/
Buffer & operator = (const Buffer & o);
/* --------------------------------------------------------------------------------------------
* Copy assignment operator.
*/
Buffer & operator = (Buffer && o)
{
if (m_Ptr != o.m_Ptr)
{
if (m_Ptr)
{
Release();
}
m_Ptr = o.m_Ptr;
m_Cap = o.m_Cap;
m_Cur = o.m_Cur;
m_Mem = o.m_Mem;
o.m_Ptr = nullptr;
}
return *this;
}
/* --------------------------------------------------------------------------------------------
* Equality comparison operator.
*/
bool operator == (const Buffer & o) const
{
return (m_Cap == o.m_Cap);
}
/* --------------------------------------------------------------------------------------------
* Inequality comparison operator.
*/
bool operator != (const Buffer & o) const
{
return (m_Cap != o.m_Cap);
}
/* --------------------------------------------------------------------------------------------
* Less than comparison operator.
*/
bool operator < (const Buffer & o) const
{
return (m_Cap < o.m_Cap);
}
/* --------------------------------------------------------------------------------------------
* Greater than comparison operator.
*/
bool operator > (const Buffer & o) const
{
return (m_Cap > o.m_Cap);
}
/* --------------------------------------------------------------------------------------------
* Less than or equal comparison operator.
*/
bool operator <= (const Buffer & o) const
{
return (m_Cap <= o.m_Cap);
}
/* --------------------------------------------------------------------------------------------
* Greater than or equal comparison operator.
*/
bool operator >= (const Buffer & o) const
{
return (m_Cap >= o.m_Cap);
}
/* --------------------------------------------------------------------------------------------
* Implicit conversion to boolean.
*/
operator bool () const
{
return m_Ptr;
}
/* --------------------------------------------------------------------------------------------
* Retrieve the internal buffer.
*/
Pointer Data()
{
return m_Ptr;
}
/* --------------------------------------------------------------------------------------------
* Retrieve the internal buffer.
*/
ConstPtr Data() const
{
return m_Ptr;
}
/* --------------------------------------------------------------------------------------------
* Retrieve the internal buffer casted as a different type.
*/
template < typename T = Value > T * Get()
{
return reinterpret_cast< T * >(m_Ptr);
}
/* --------------------------------------------------------------------------------------------
* Retrieve the internal buffer casted as a different type.
*/
template < typename T = Value > const T * Get() const
{
return reinterpret_cast< const T * >(m_Ptr);
}
/* --------------------------------------------------------------------------------------------
* Retrieve a certain element type at the specified position.
*/
template < typename T = Value > T & At(SzType n)
{
assert(n < static_cast< SzType >(m_Cap / sizeof(T)));
return reinterpret_cast< T * >(m_Ptr)[n];
}
/* --------------------------------------------------------------------------------------------
* Retrieve a certain element type at the specified position.
*/
template < typename T = Value > const T & At(SzType n) const
{
assert(n < static_cast< SzType >(m_Cap / sizeof(T)));
return reinterpret_cast< const T * >(m_Ptr)[n];
}
/* --------------------------------------------------------------------------------------------
* Retrieve the internal buffer casted as a different type.
*/
template < typename T = Value > T * Begin()
{
return reinterpret_cast< T * >(m_Ptr);
}
/* --------------------------------------------------------------------------------------------
* Retrieve the internal buffer casted as a different type.
*/
template < typename T = Value > const T * Begin() const
{
return reinterpret_cast< const T * >(m_Ptr);
}
/* --------------------------------------------------------------------------------------------
* Retrieve the internal buffer casted as a different type.
*/
template < typename T = Value > T * End()
{
return reinterpret_cast< T * >(m_Ptr) + (m_Cap / sizeof(T));
}
/* --------------------------------------------------------------------------------------------
* Retrieve the internal buffer casted as a different type.
*/
template < typename T = Value > const T * End() const
{
return reinterpret_cast< const T * >(m_Ptr) + (m_Cap / sizeof(T));
}
/* --------------------------------------------------------------------------------------------
* Retrieve the element at the front of the buffer.
*/
template < typename T = Value > T & Front()
{
assert(m_Cap >= sizeof(T));
return reinterpret_cast< T * >(m_Ptr)[0];
}
/* --------------------------------------------------------------------------------------------
* Retrieve the element at the front of the buffer.
*/
template < typename T = Value > const T & Front() const
{
assert(m_Cap >= sizeof(T));
return reinterpret_cast< const T * >(m_Ptr)[0];
}
/* --------------------------------------------------------------------------------------------
* Retrieve the element after the first element in the buffer.
*/
template < typename T = Value > T & Next()
{
assert(m_Cap >= (sizeof(T) * 2));
return reinterpret_cast< T * >(m_Ptr)[1];
}
/* --------------------------------------------------------------------------------------------
* Retrieve the element after the first element in the buffer.
*/
template < typename T = Value > const T & Next() const
{
assert(m_Cap >= (sizeof(T) * 2));
return reinterpret_cast< const T * >(m_Ptr)[1];
}
/* --------------------------------------------------------------------------------------------
* Retrieve the element at the back of the buffer.
*/
template < typename T = Value > T & Back()
{
assert(m_Cap >= sizeof(T));
return reinterpret_cast< T * >(m_Ptr)[(m_Cap / sizeof(T))-1];
}
/* --------------------------------------------------------------------------------------------
* Retrieve the element at the back of the buffer.
*/
template < typename T = Value > const T & Back() const
{
assert(m_Cap >= sizeof(T));
return reinterpret_cast< const T * >(m_Ptr)[(m_Cap / sizeof(T))-1];
}
/* --------------------------------------------------------------------------------------------
* Retrieve the element before the last element in the buffer.
*/
template < typename T = Value > T & Prev()
{
assert(m_Cap >= (sizeof(T) * 2));
return reinterpret_cast< T * >(m_Ptr)[(m_Cap / sizeof(T))-2];
}
/* --------------------------------------------------------------------------------------------
* Retrieve the element before the last element in the buffer.
*/
template < typename T = Value > const T & Prev() const
{
assert(m_Cap >= (sizeof(T) * 2));
return reinterpret_cast< const T * >(m_Ptr)[(m_Cap / sizeof(T))-2];
}
/* --------------------------------------------------------------------------------------------
* Reposition the edit cursor to the specified number of elements ahead.
*/
template < typename T = Value > void Advance(SzType n)
{
// Do we need to scale the buffer?
if ((m_Cur + (n * sizeof(T))) >= m_Cap)
{
Grow(m_Cur + (n * sizeof(T)));
}
// Advance to the specified position
m_Cur += (n * sizeof(T));
}
/* --------------------------------------------------------------------------------------------
* Reposition the edit cursor to the specified number of elements behind.
*/
template < typename T = Value > void Retreat(SzType n)
{
// Can we move that much backward?
if ((n * sizeof(T)) <= m_Cur)
{
m_Cur -= (n * sizeof(T));
}
// Just got to the beginning
else
{
m_Cur = 0;
}
}
/* --------------------------------------------------------------------------------------------
* Reposition the edit cursor to a fixed position within the buffer.
*/
template < typename T = Value > void Move(SzType n)
{
// Do we need to scale the buffer?
if ((n * sizeof(T)) >= m_Cap)
{
Grow(n * sizeof(T));
}
// Move to the specified position
m_Cur = (n * sizeof(T));
}
/* --------------------------------------------------------------------------------------------
* Append a value to the current cursor location and advance the cursor.
*/
template < typename T = Value > void Push(T v)
{
// Do we need to scale the buffer?
if ((m_Cur + sizeof(T)) >= m_Cap)
{
Grow(m_Cap + sizeof(T));
}
// Assign the specified value
reinterpret_cast< T * >(m_Ptr)[m_Cur] = v;
// Move to the next element
m_Cur += sizeof(T);
}
/* --------------------------------------------------------------------------------------------
* Retrieve the element at the cursor position.
*/
template < typename T = Value > T & Cursor()
{
assert((m_Cur / sizeof(T)) < (m_Cap / sizeof(T)));
return reinterpret_cast< T * >(m_Ptr)[m_Cur];
}
/* --------------------------------------------------------------------------------------------
* Retrieve the element at the cursor position.
*/
template < typename T = Value > const T & Cursor() const
{
assert((m_Cur / sizeof(T)) < (m_Cap / sizeof(T)));
return reinterpret_cast< const T * >(m_Ptr)[m_Cur];
}
/* --------------------------------------------------------------------------------------------
* Retrieve the element before the cursor position.
*/
template < typename T = Value > T & Before()
{
assert(m_Cur >= sizeof(T));
return reinterpret_cast< T * >(m_Ptr)[(m_Cur / sizeof(T))-1];
}
/* --------------------------------------------------------------------------------------------
* Retrieve the element before the cursor position.
*/
template < typename T = Value > const T & Before() const
{
assert(m_Cur >= sizeof(T));
return reinterpret_cast< const T * >(m_Ptr)[(m_Cur / sizeof(T))-1];
}
/* --------------------------------------------------------------------------------------------
* Retrieve the element after the cursor position.
*/
template < typename T = Value > T & After()
{
assert(m_Cap >= sizeof(T) && (m_Cur + sizeof(T)) <= (m_Cap - sizeof(T)));
return reinterpret_cast< T * >(m_Ptr)[(m_Cur / sizeof(T))+1];
}
/* --------------------------------------------------------------------------------------------
* Retrieve the element after the cursor position.
*/
template < typename T = Value > const T & After() const
{
assert(m_Cap >= sizeof(T) && (m_Cur + sizeof(T)) <= (m_Cap - sizeof(T)));
return reinterpret_cast< const T * >(m_Ptr)[(m_Cur / sizeof(T))+1];
}
/* --------------------------------------------------------------------------------------------
* Retrieve maximum elements it can hold for a certain type.
*/
template < typename T = Value > static SzType Max()
{
return static_cast< SzType >(0xFFFFFFFF / sizeof(T));
}
/* --------------------------------------------------------------------------------------------
* Retrieve the current buffer capacity in element count.
*/
template < typename T = Value > SzType Size() const
{
return static_cast< SzType >(m_Cap / sizeof(T));
}
/* --------------------------------------------------------------------------------------------
* Retrieve the current buffer capacity in byte count.
*/
SzType Capacity() const
{
return m_Cap;
}
/* --------------------------------------------------------------------------------------------
* Retrieve the current position of the cursor in the buffer.
*/
template < typename T = Value > SzType Position() const
{
return static_cast< SzType >(m_Cur / sizeof(T));
}
/* --------------------------------------------------------------------------------------------
* Retrieve the amount of unused buffer after the edit cursor.
*/
template < typename T = Value > SzType Remaining() const
{
return static_cast< SzType >((m_Cap - m_Cur) / sizeof(T));
}
/* --------------------------------------------------------------------------------------------
* Grow the size of the internal buffer by the specified amount of bytes.
*/
void Grow(SzType n);
/* --------------------------------------------------------------------------------------------
* Makes sure there is enough capacity to hold the specified element count.
*/
template < typename T = Value > Buffer Adjust(SzType n)
{
// Do we meet the minimum size?
if (n < 8)
{
n = 8; // Adjust to minimum size
}
// See if the requested capacity doesn't exceed the limit
if (n > Max< T >())
{
ThrowMemExcept("Requested buffer of (%u) elements exceeds the (%u) limit", n, Max< T >());
}
// Is there an existing buffer?
else if (n && !m_Cap)
{
Request(n * sizeof(T)); // Request the memory
}
// Should the size be increased?
else if (n > m_Cap)
{
// Backup the current memory
Buffer bkp(m_Ptr, m_Cap, m_Cur, m_Mem);
// Request the memory
Request(n * sizeof(T));
// Return the backup
return std::move(bkp);
}
// Return an empty buffer
return Buffer();
}
/* --------------------------------------------------------------------------------------------
* Release the managed memory.
*/
void Reset()
{
if (m_Ptr)
{
Release();
}
}
/* --------------------------------------------------------------------------------------------
* Release the managed memory and manager.
*/
void ResetAll()
{
if (m_Ptr)
{
Release();
}
m_Mem.Reset();
}
/* --------------------------------------------------------------------------------------------
* Swap the contents of two buffers.
*/
void Swap(Buffer & o)
{
Pointer p = m_Ptr;
SzType n = m_Cap;
m_Ptr = o.m_Ptr;
m_Cap = o.m_Cap;
o.m_Ptr = p;
o.m_Cap = n;
}
/* --------------------------------------------------------------------------------------------
* Write a portion of a buffer to the internal buffer.
*/
SzType Write(SzType pos, ConstPtr data, SzType size);
/* --------------------------------------------------------------------------------------------
* Write another buffer to the internal buffer.
*/
SzType Write(SzType pos, const Buffer & b)
{
return Write(pos, b.m_Ptr, b.m_Cur);
}
/* --------------------------------------------------------------------------------------------
* Write a formatted string to the internal buffer.
*/
SzType WriteF(SzType pos, const char * fmt, ...);
/* --------------------------------------------------------------------------------------------
* Write a formatted string to the internal buffer.
*/
SzType WriteF(SzType pos, const char * fmt, va_list args);
/* --------------------------------------------------------------------------------------------
* Write a string to the internal buffer.
*/
SzType WriteS(SzType pos, const char * str);
/* --------------------------------------------------------------------------------------------
* Write a portion of a string to the internal buffer.
*/
SzType WriteS(SzType pos, const char * str, SzType size)
{
return Write(pos, str, size);
}
/* --------------------------------------------------------------------------------------------
* Append a portion of a buffer to the internal buffer.
*/
void Append(ConstPtr data, SzType size)
{
m_Cur += Write(m_Cur, data, size);
}
/* --------------------------------------------------------------------------------------------
* Append another buffer to the internal buffer.
*/
void Append(const Buffer & b)
{
m_Cur += Write(m_Cur, b.m_Ptr, b.m_Cur);
}
/* --------------------------------------------------------------------------------------------
* Append a formatted string to the internal buffer.
*/
void AppendF(const char * fmt, ...);
/* --------------------------------------------------------------------------------------------
* Append a formatted string to the internal buffer.
*/
void AppendF(const char * fmt, va_list args)
{
m_Cur += WriteF(m_Cur, fmt, args);
}
/* --------------------------------------------------------------------------------------------
* Append a string to the internal buffer.
*/
void AppendS(const char * str);
/* --------------------------------------------------------------------------------------------
* Append a portion of a string to the internal buffer.
*/
void AppendS(const char * str, SzType size)
{
m_Cur += Write(m_Cur, str, size);
}
protected:
/* --------------------------------------------------------------------------------------------
* Request the memory specified in the capacity.
*/
void Request(SzType n);
/* --------------------------------------------------------------------------------------------
* Release the managed memory buffer.
*/
void Release();
private:
// --------------------------------------------------------------------------------------------
Pointer m_Ptr; /* Pointer to the memory buffer. */
SzType m_Cap; /* The total size of the buffer. */
SzType m_Cur; /* The buffer edit cursor. */
// --------------------------------------------------------------------------------------------
MemRef m_Mem; /* Reference to the associated memory manager. */
};
} // Namespace:: SqMod
#endif // _BASE_BUFFER_HPP_

View File

@ -513,11 +513,11 @@ void Register_Circle(HSQUIRRELVM vm)
.Var(_SC("Rad"), &Circle::rad)
// Properties
.Prop(_SC("Abs"), &Circle::Abs)
// Core Metamethods
// Core Meta-methods
.Func(_SC("_tostring"), &Circle::ToString)
.SquirrelFunc(_SC("_typename"), &Circle::Typename)
.Func(_SC("_cmp"), &Circle::Cmp)
// Metamethods
// Meta-methods
.Func< Circle (Circle::*)(const Circle &) const >(_SC("_add"), &Circle::operator +)
.Func< Circle (Circle::*)(const Circle &) const >(_SC("_sub"), &Circle::operator -)
.Func< Circle (Circle::*)(const Circle &) const >(_SC("_mul"), &Circle::operator *)

View File

@ -661,11 +661,11 @@ void Register_Color3(HSQUIRRELVM vm)
.Prop(_SC("RGBA"), &Color3::GetRGBA, &Color3::SetRGBA)
.Prop(_SC("ARGB"), &Color3::GetARGB, &Color3::SetARGB)
.Prop(_SC("Str"), &Color3::SetCol)
// Core Metamethods
// Core Meta-methods
.Func(_SC("_tostring"), &Color3::ToString)
.SquirrelFunc(_SC("_typename"), &Color3::Typename)
.Func(_SC("_cmp"), &Color3::Cmp)
// Metamethods
// Meta-methods
.Func< Color3 (Color3::*)(const Color3 &) const >(_SC("_add"), &Color3::operator +)
.Func< Color3 (Color3::*)(const Color3 &) const >(_SC("_sub"), &Color3::operator -)
.Func< Color3 (Color3::*)(const Color3 &) const >(_SC("_mul"), &Color3::operator *)

View File

@ -721,11 +721,11 @@ void Register_Color4(HSQUIRRELVM vm)
.Prop(_SC("RGBA"), &Color4::GetRGBA, &Color4::SetRGBA)
.Prop(_SC("ARGB"), &Color4::GetARGB, &Color4::SetARGB)
.Prop(_SC("Str"), &Color4::SetCol)
// Core Metamethods
// Core Meta-methods
.Func(_SC("_tostring"), &Color4::ToString)
.SquirrelFunc(_SC("_typename"), &Color4::Typename)
.Func(_SC("_cmp"), &Color4::Cmp)
// Metamethods
// Meta-methods
.Func< Color4 (Color4::*)(const Color4 &) const >(_SC("_add"), &Color4::operator +)
.Func< Color4 (Color4::*)(const Color4 &) const >(_SC("_sub"), &Color4::operator -)
.Func< Color4 (Color4::*)(const Color4 &) const >(_SC("_mul"), &Color4::operator *)

View File

@ -516,11 +516,11 @@ void Register_Quaternion(HSQUIRRELVM vm)
.Var(_SC("W"), &Quaternion::w)
// Properties
.Prop(_SC("Abs"), &Quaternion::Abs)
// Core Metamethods
// Core Meta-methods
.Func(_SC("_tostring"), &Quaternion::ToString)
.SquirrelFunc(_SC("_typename"), &Quaternion::Typename)
.Func(_SC("_cmp"), &Quaternion::Cmp)
// Metamethods
// Meta-methods
.Func< Quaternion (Quaternion::*)(const Quaternion &) const >(_SC("_add"), &Quaternion::operator +)
.Func< Quaternion (Quaternion::*)(const Quaternion &) const >(_SC("_sub"), &Quaternion::operator -)
.Func< Quaternion (Quaternion::*)(const Quaternion &) const >(_SC("_mul"), &Quaternion::operator *)

View File

@ -7,27 +7,12 @@
#include "Library/Numeric.hpp"
// ------------------------------------------------------------------------------------------------
#include <ctime>
#include <cfloat>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
// ------------------------------------------------------------------------------------------------
namespace SqMod {
// ------------------------------------------------------------------------------------------------
PluginFuncs* _Func = nullptr;
PluginCallbacks* _Clbk = nullptr;
PluginInfo* _Info = nullptr;
/* ------------------------------------------------------------------------------------------------
* Common buffer to reduce memory allocations. To be immediately copied upon return!
*/
static SQChar g_Buffer[4096];
static SQChar g_NumBuff[1024];
// ------------------------------------------------------------------------------------------------
static const Color3 SQ_Color_List[] =
{
@ -216,115 +201,6 @@ const ULongInt & GetULongInt(CSStr s)
return l;
}
// ------------------------------------------------------------------------------------------------
Object & NullObject()
{
static Object o;
o.Release();
return o;
}
// ------------------------------------------------------------------------------------------------
Table & NullTable()
{
static Table t;
t.Release();
return t;
}
// ------------------------------------------------------------------------------------------------
Array & NullArray()
{
static Array a;
a.Release();
return a;
}
// ------------------------------------------------------------------------------------------------
Function & NullFunction()
{
static Function f;
f.Release();
return f;
}
// ------------------------------------------------------------------------------------------------
bool SToB(CSStr str)
{
// Temporary buffer to store the lowercase string
SQChar buffer[8];
// The currently processed character
unsigned i = 0;
// Convert only the necessary characters to lowercase
while (i < 7 && *str != '\0')
{
buffer[i++] = static_cast< SQChar >(std::tolower(*(str++)));
}
// Add the null terminator
buffer[i] = '\0';
// Compare the lowercase string and return the result
return (std::strcmp(buffer, "true") == 0 || std::strcmp(buffer, "yes") == 0 ||
std::strcmp(buffer, "on") == 0 || std::strcmp(buffer, "1") == 0) ? true : false;
}
// ------------------------------------------------------------------------------------------------
void SqThrowF(CSStr fmt, ...)
{
// Acquire a moderately sized buffer
Buffer b(128);
// Initialize the argument list
va_list args;
va_start (args, fmt);
// Attempt to run the specified format
if (b.WriteF(0, fmt, args) == 0)
{
// Attempt to write a generic message at least
b.At(b.WriteS(0, "Unknown error has occurred")) = '\0';
}
// Release the argument list
va_end(args);
// Throw the exception with the resulted message
throw Sqrat::Exception(b.Get< SQChar >());
}
// ------------------------------------------------------------------------------------------------
CSStr ToStrF(CSStr fmt, ...)
{
// Prepare the arguments list
va_list args;
va_start(args, fmt);
// Attempt to run the specified format
int ret = vsnprintf(g_Buffer, sizeof(g_Buffer), fmt, args);
// See if the format function failed
if (ret < 0)
{
STHROWF("Failed to run the specified string format");
}
// Finalized the arguments list
va_end(args);
// Return the resulted string
return g_Buffer;
}
// ------------------------------------------------------------------------------------------------
CSStr ToStringF(CSStr fmt, ...)
{
// Acquire a moderately sized buffer
Buffer b(128);
// Prepare the arguments list
va_list args;
va_start (args, fmt);
// Attempt to run the specified format
if (b.WriteF(0, fmt, args) == 0)
{
// Make sure the string is null terminated
b.At(0) = 0;
}
// Finalized the arguments list
va_end(args);
// Return the resulted string
return b.Get< SQChar >();
}
// ------------------------------------------------------------------------------------------------
const Color3 & GetRandomColor()
{
@ -937,303 +813,6 @@ Color3 GetColor(CSStr name)
}
}
// ------------------------------------------------------------------------------------------------
CSStr ConvNum< Int8 >::ToStr(Int8 v)
{
// Write the numeric value to the buffer
if (std::snprintf(g_NumBuff, sizeof(g_NumBuff), "%d", v) < 0)
{
g_NumBuff[0] = '\0';
}
// Return the beginning of the buffer
return g_NumBuff;
}
Int8 ConvNum< Int8 >::FromStr(CSStr s)
{
return ConvTo< Int8 >::From(std::strtol(s, nullptr, 10));
}
Int8 ConvNum< Int8 >::FromStr(CSStr s, Int32 base)
{
return ConvTo< Int8 >::From(std::strtol(s, nullptr, base));
}
// ------------------------------------------------------------------------------------------------
CSStr ConvNum< Uint8 >::ToStr(Uint8 v)
{
// Write the numeric value to the buffer
if (std::snprintf(g_NumBuff, sizeof(g_NumBuff), "%u", v) < 0)
{
g_NumBuff[0] = '\0';
}
// Return the beginning of the buffer
return g_NumBuff;
}
Uint8 ConvNum< Uint8 >::FromStr(CSStr s)
{
return ConvTo< Uint8 >::From(std::strtoul(s, nullptr, 10));
}
Uint8 ConvNum< Uint8 >::FromStr(CSStr s, Int32 base)
{
return ConvTo< Uint8 >::From(std::strtoul(s, nullptr, base));
}
// ------------------------------------------------------------------------------------------------
CSStr ConvNum< Int16 >::ToStr(Int16 v)
{
// Write the numeric value to the buffer
if (std::snprintf(g_NumBuff, sizeof(g_NumBuff), "%d", v) < 0)
{
g_NumBuff[0] = '\0';
}
// Return the beginning of the buffer
return g_NumBuff;
}
Int16 ConvNum< Int16 >::FromStr(CSStr s)
{
return ConvTo< Int16 >::From(std::strtol(s, nullptr, 10));
}
Int16 ConvNum< Int16 >::FromStr(CSStr s, Int32 base)
{
return ConvTo< Int16 >::From(std::strtol(s, nullptr, base));
}
// ------------------------------------------------------------------------------------------------
CSStr ConvNum< Uint16 >::ToStr(Uint16 v)
{
// Write the numeric value to the buffer
if (std::snprintf(g_NumBuff, sizeof(g_NumBuff), "%u", v) < 0)
{
g_NumBuff[0] = '\0';
}
// Return the beginning of the buffer
return g_NumBuff;
}
Uint16 ConvNum< Uint16 >::FromStr(CSStr s)
{
return ConvTo< Uint16 >::From(std::strtoul(s, nullptr, 10));
}
Uint16 ConvNum< Uint16 >::FromStr(CSStr s, Int32 base)
{
return ConvTo< Uint16 >::From(std::strtoul(s, nullptr, base));
}
// ------------------------------------------------------------------------------------------------
CSStr ConvNum< Int32 >::ToStr(Int32 v)
{
// Write the numeric value to the buffer
if (std::snprintf(g_NumBuff, sizeof(g_NumBuff), "%d", v) < 0)
{
g_NumBuff[0] = '\0';
}
// Return the beginning of the buffer
return g_NumBuff;
}
Int32 ConvNum< Int32 >::FromStr(CSStr s)
{
return ConvTo< Int32 >::From(std::strtol(s, nullptr, 10));
}
Int32 ConvNum< Int32 >::FromStr(CSStr s, Int32 base)
{
return ConvTo< Int32 >::From(std::strtol(s, nullptr, base));
}
// ------------------------------------------------------------------------------------------------
CSStr ConvNum< Uint32 >::ToStr(Uint32 v)
{
// Write the numeric value to the buffer
if (std::snprintf(g_NumBuff, sizeof(g_NumBuff), "%u", v) < 0)
{
g_NumBuff[0] = '\0';
}
// Return the beginning of the buffer
return g_NumBuff;
}
Uint32 ConvNum< Uint32 >::FromStr(CSStr s)
{
return ConvTo< Uint32 >::From(std::strtoul(s, nullptr, 10));
}
Uint32 ConvNum< Uint32 >::FromStr(CSStr s, Int32 base)
{
return ConvTo< Uint32 >::From(std::strtoul(s, nullptr, base));
}
// ------------------------------------------------------------------------------------------------
CSStr ConvNum< Int64 >::ToStr(Int64 v)
{
// Write the numeric value to the buffer
if (std::snprintf(g_NumBuff, sizeof(g_NumBuff), "%lld", v) < 0)
{
g_NumBuff[0] = '\0';
}
// Return the beginning of the buffer
return g_NumBuff;
}
Int64 ConvNum< Int64 >::FromStr(CSStr s)
{
return std::strtoll(s, nullptr, 10);
}
Int64 ConvNum< Int64 >::FromStr(CSStr s, Int32 base)
{
return std::strtoll(s, nullptr, base);
}
// ------------------------------------------------------------------------------------------------
CSStr ConvNum< Uint64 >::ToStr(Uint64 v)
{
// Write the numeric value to the buffer
if (std::snprintf(g_NumBuff, sizeof(g_NumBuff), "%llu", v) < 0)
{
g_NumBuff[0] = '\0';
}
// Return the beginning of the buffer
return g_NumBuff;
}
Uint64 ConvNum< Uint64 >::FromStr(CSStr s)
{
return std::strtoull(s, nullptr, 10);
}
Uint64 ConvNum< Uint64 >::FromStr(CSStr s, Int32 base)
{
return std::strtoull(s, nullptr, base);
}
// ------------------------------------------------------------------------------------------------
CSStr ConvNum< LongI >::ToStr(LongI v)
{
// Write the numeric value to the buffer
if (std::snprintf(g_NumBuff, sizeof(g_NumBuff), "%ld", v) < 0)
{
g_NumBuff[0] = '\0';
}
// Return the beginning of the buffer
return g_NumBuff;
}
LongI ConvNum< LongI >::FromStr(CSStr s)
{
return std::strtol(s, nullptr, 10);
}
LongI ConvNum< LongI >::FromStr(CSStr s, Int32 base)
{
return std::strtol(s, nullptr, base);
}
// ------------------------------------------------------------------------------------------------
CSStr ConvNum< Ulong >::ToStr(Ulong v)
{
// Write the numeric value to the buffer
if (std::snprintf(g_NumBuff, sizeof(g_NumBuff), "%lu", v) < 0)
{
g_NumBuff[0] = '\0';
}
// Return the beginning of the buffer
return g_NumBuff;
}
Ulong ConvNum< Ulong >::FromStr(CSStr s)
{
return std::strtoul(s, nullptr, 10);
}
Ulong ConvNum< Ulong >::FromStr(CSStr s, Int32 base)
{
return std::strtoul(s, nullptr, base);
}
// ------------------------------------------------------------------------------------------------
CSStr ConvNum< Float32 >::ToStr(Float32 v)
{
// Attempt to convert the value to a string
if (std::snprintf(g_NumBuff, sizeof(g_NumBuff), "%f", v) < 0)
{
g_NumBuff[0] = '\0';
}
// Return the data from the buffer
return g_NumBuff;
}
Float32 ConvNum< Float32 >::FromStr(CSStr s)
{
return std::strtof(s, nullptr);
}
Float32 ConvNum< Float32 >::FromStr(CSStr s, Int32 /*base*/)
{
return std::strtof(s, nullptr);
}
// ------------------------------------------------------------------------------------------------
CSStr ConvNum< Float64 >::ToStr(Float64 v)
{
// Attempt to convert the value to a string
if (std::snprintf(g_NumBuff, sizeof(g_NumBuff), "%f", v) < 0)
{
g_NumBuff[0] = '\0';
}
// Return the data from the buffer
return g_NumBuff;
}
Float64 ConvNum< Float64 >::FromStr(CSStr s)
{
return std::strtod(s, nullptr);
}
Float64 ConvNum< Float64 >::FromStr(CSStr s, Int32 /*base*/)
{
return std::strtod(s, nullptr);
}
// ------------------------------------------------------------------------------------------------
CSStr ConvNum< bool >::ToStr(bool v)
{
if (v)
{
g_NumBuff[0] = 't';
g_NumBuff[1] = 'r';
g_NumBuff[2] = 'u';
g_NumBuff[3] = 'e';
g_NumBuff[4] = '\0';
}
else
{
g_NumBuff[0] = 'f';
g_NumBuff[1] = 'a';
g_NumBuff[2] = 'l';
g_NumBuff[3] = 's';
g_NumBuff[4] = 'e';
g_NumBuff[5] = '\0';
}
return g_NumBuff;
}
bool ConvNum< bool >::FromStr(CSStr s)
{
return (std::strcmp(s, "true") == 0) ? true : false;
}
bool ConvNum< bool >::FromStr(CSStr s, Int32 /*base*/)
{
return (std::strcmp(s, "true") == 0) ? true : false;
}
// ================================================================================================
void Register_Base(HSQUIRRELVM vm)
{

File diff suppressed because it is too large Load Diff

View File

@ -514,11 +514,11 @@ void Register_Sphere(HSQUIRRELVM vm)
.Var(_SC("Rad"), &Sphere::rad)
// Properties
.Prop(_SC("Abs"), &Sphere::Abs)
// Core Metamethods
// Core Meta-methods
.Func(_SC("_tostring"), &Sphere::ToString)
.SquirrelFunc(_SC("_typename"), &Sphere::Typename)
.Func(_SC("_cmp"), &Sphere::Cmp)
// Metamethods
// Meta-methods
.Func< Sphere (Sphere::*)(const Sphere &) const >(_SC("_add"), &Sphere::operator +)
.Func< Sphere (Sphere::*)(const Sphere &) const >(_SC("_sub"), &Sphere::operator -)
.Func< Sphere (Sphere::*)(const Sphere &) const >(_SC("_mul"), &Sphere::operator *)

View File

@ -1,413 +0,0 @@
// ------------------------------------------------------------------------------------------------
#include "Base/Stack.hpp"
#include "Base/Shared.hpp"
#include "Base/Buffer.hpp"
#include "Library/Numeric.hpp"
// ------------------------------------------------------------------------------------------------
#include <sqstdstring.h>
// ------------------------------------------------------------------------------------------------
namespace SqMod {
// ------------------------------------------------------------------------------------------------
SQInteger PopStackInteger(HSQUIRRELVM vm, SQInteger idx)
{
// Identify which type must be extracted
switch (sq_gettype(vm, idx))
{
case OT_INTEGER:
{
SQInteger val;
sq_getinteger(vm, idx, &val);
return val;
} break;
case OT_FLOAT:
{
SQFloat val;
sq_getfloat(vm, idx, &val);
return ConvTo< SQInteger >::From(val);
} break;
case OT_BOOL:
{
SQBool val;
sq_getbool(vm, idx, &val);
return static_cast< SQInteger >(val);
} break;
case OT_STRING:
{
CSStr val = nullptr;
// Attempt to retrieve and convert the string
if (SQ_SUCCEEDED(sq_getstring(vm, idx, &val)) && val != nullptr && *val != '\0')
{
return ConvTo< SQInteger >::From(std::strtoll(val, nullptr, 10));
}
} break;
case OT_ARRAY:
case OT_TABLE:
case OT_CLASS:
case OT_USERDATA:
{
return sq_getsize(vm, idx);
} break;
case OT_INSTANCE:
{
// Attempt to treat the value as a signed long instance
try
{
return ConvTo< SQInteger >::From(Var< const SLongInt & >(vm, idx).value.GetNum());
}
catch (...)
{
// Just ignore it...
}
// Attempt to treat the value as a unsigned long instance
try
{
return ConvTo< SQInteger >::From(Var< const ULongInt & >(vm, idx).value.GetNum());
}
catch (...)
{
// Just ignore it...
}
// Attempt to get the size of the instance as a fallback
return sq_getsize(vm, idx);
} break;
default: break;
}
// Default to 0
return 0;
}
// ------------------------------------------------------------------------------------------------
SQFloat PopStackFloat(HSQUIRRELVM vm, SQInteger idx)
{
// Identify which type must be extracted
switch (sq_gettype(vm, idx))
{
case OT_FLOAT:
{
SQFloat val;
sq_getfloat(vm, idx, &val);
return val;
} break;
case OT_INTEGER:
{
SQInteger val;
sq_getinteger(vm, idx, &val);
return ConvTo< SQFloat >::From(val);
} break;
case OT_BOOL:
{
SQBool val;
sq_getbool(vm, idx, &val);
return ConvTo< SQFloat >::From(val);
} break;
case OT_STRING:
{
CSStr val = nullptr;
// Attempt to retrieve and convert the string
if (SQ_SUCCEEDED(sq_getstring(vm, idx, &val)) && val != nullptr && *val != '\0')
{
#ifdef SQUSEDOUBLE
return std::strtod(val, nullptr);
#else
return std::strtof(val, nullptr);
#endif // SQUSEDOUBLE
}
} break;
case OT_ARRAY:
case OT_TABLE:
case OT_CLASS:
case OT_USERDATA:
{
return ConvTo< SQFloat >::From(sq_getsize(vm, idx));
} break;
case OT_INSTANCE:
{
// Attempt to treat the value as a signed long instance
try
{
return ConvTo< SQFloat >::From(Var< const SLongInt & >(vm, idx).value.GetNum());
}
catch (...)
{
// Just ignore it...
}
// Attempt to treat the value as a unsigned long instance
try
{
return ConvTo< SQFloat >::From(Var< const ULongInt & >(vm, idx).value.GetNum());
}
catch (...)
{
// Just ignore it...
}
// Attempt to get the size of the instance as a fallback
return ConvTo< SQFloat >::From(sq_getsize(vm, idx));
} break;
default: break;
}
// Default to 0
return 0.0;
}
// ------------------------------------------------------------------------------------------------
Int64 PopStackLong(HSQUIRRELVM vm, SQInteger idx)
{
// Identify which type must be extracted
switch (sq_gettype(vm, idx))
{
case OT_INTEGER:
{
SQInteger val;
sq_getinteger(vm, idx, &val);
return static_cast< Int64 >(val);
} break;
case OT_FLOAT:
{
SQFloat val;
sq_getfloat(vm, idx, &val);
return ConvTo< Int64 >::From(val);
} break;
case OT_BOOL:
{
SQBool val;
sq_getbool(vm, idx, &val);
return static_cast< Int64 >(val);
} break;
case OT_STRING:
{
CSStr val = nullptr;
// Attempt to retrieve and convert the string
if (SQ_SUCCEEDED(sq_getstring(vm, idx, &val)) && val != nullptr && *val != '\0')
{
return std::strtoll(val, nullptr, 10);
}
} break;
case OT_ARRAY:
case OT_TABLE:
case OT_CLASS:
case OT_USERDATA:
{
return static_cast< Int64 >(sq_getsize(vm, idx));
} break;
case OT_INSTANCE:
{
// Attempt to treat the value as a signed long instance
try
{
return Var< const SLongInt & >(vm, idx).value.GetNum();
}
catch (...)
{
// Just ignore it...
}
// Attempt to treat the value as a unsigned long instance
try
{
return ConvTo< Int64 >::From(Var< const ULongInt & >(vm, idx).value.GetNum());
}
catch (...)
{
// Just ignore it...
}
// Attempt to get the size of the instance as a fallback
return static_cast< Int64 >(sq_getsize(vm, idx));
} break;
default: break;
}
// Default to 0
return 0;
}
// ------------------------------------------------------------------------------------------------
Uint64 PopStackULong(HSQUIRRELVM vm, SQInteger idx)
{
// Identify which type must be extracted
switch (sq_gettype(vm, idx))
{
case OT_INTEGER:
{
SQInteger val;
sq_getinteger(vm, idx, &val);
return ConvTo< Uint64 >::From(val);
} break;
case OT_FLOAT:
{
SQFloat val;
sq_getfloat(vm, idx, &val);
return ConvTo< Uint64 >::From(val);
} break;
case OT_BOOL:
{
SQBool val;
sq_getbool(vm, idx, &val);
return ConvTo< Uint64 >::From(val);
} break;
case OT_STRING:
{
CSStr val = nullptr;
// Attempt to retrieve and convert the string
if (SQ_SUCCEEDED(sq_getstring(vm, idx, &val)) && val != nullptr && *val != '\0')
{
return std::strtoull(val, nullptr, 10);
}
} break;
case OT_ARRAY:
case OT_TABLE:
case OT_CLASS:
case OT_USERDATA:
{
return ConvTo< Uint64 >::From(sq_getsize(vm, idx));
} break;
case OT_INSTANCE:
{
// Attempt to treat the value as a signed long instance
try
{
return ConvTo< Uint64 >::From(Var< const SLongInt & >(vm, idx).value.GetNum());
}
catch (...)
{
// Just ignore it...
}
// Attempt to treat the value as a unsigned long instance
try
{
return Var< const ULongInt & >(vm, idx).value.GetNum();
}
catch (...)
{
// Just ignore it...
}
// Attempt to get the size of the instance as a fallback
return ConvTo< Uint64 >::From(sq_getsize(vm, idx));
} break;
default: break;
}
// Default to 0
return 0;
}
// --------------------------------------------------------------------------------------------
StackStrF::StackStrF(HSQUIRRELVM vm, SQInteger idx, bool fmt)
: mPtr(nullptr)
, mLen(-1)
, mRes(SQ_OK)
, mObj()
, mVM(vm)
{
const Int32 top = sq_gettop(vm);
// Reset the converted value object
sq_resetobject(&mObj);
// Was the string or value specified?
if (top <= (idx - 1))
{
mRes = sq_throwerror(vm, "Missing string or value");
}
// Do we have enough values to call the format function and are we allowed to?
else if (top > idx && fmt)
{
// Pointer to the generated string
SStr str = nullptr;
// Attempt to generate the specified string format
mRes = sqstd_format(vm, idx, &mLen, &str);
// Did the format succeeded but ended up with a null string pointer?
if (SQ_SUCCEEDED(mRes) && !str)
{
mRes = sq_throwerror(vm, "Unable to generate the string");
}
else
{
mPtr = const_cast< CSStr >(str);
}
}
// Is the value on the stack an actual string?
else if (sq_gettype(vm, idx) == OT_STRING)
{
// Obtain a reference to the string object
mRes = sq_getstackobj(vm, idx, &mObj);
// Could we retrieve the object from the stack?
if (SQ_SUCCEEDED(mRes))
{
// Keep a strong reference to the object
sq_addref(vm, &mObj);
// Attempt to retrieve the string value from the stack
mRes = sq_getstring(vm, idx, &mPtr);
}
// Did the retrieval succeeded but ended up with a null string pointer?
if (SQ_SUCCEEDED(mRes) && !mPtr)
{
mRes = sq_throwerror(vm, "Unable to retrieve the string");
}
}
// We have to try and convert it to string
else
{
// Attempt to convert the value from the stack to a string
mRes = sq_tostring(vm, idx);
// Could we convert the specified value to string?
if (SQ_SUCCEEDED(mRes))
{
// Obtain a reference to the resulted object
mRes = sq_getstackobj(vm, -1, &mObj);
// Could we retrieve the object from the stack?
if (SQ_SUCCEEDED(mRes))
{
// Keep a strong reference to the object
sq_addref(vm, &mObj);
// Attempt to obtain the string pointer
mRes = sq_getstring(vm, -1, &mPtr);
}
}
// Pop a value from the stack regardless of the result
sq_pop(vm, 1);
// Did the retrieval succeeded but ended up with a null string pointer?
if (SQ_SUCCEEDED(mRes) && !mPtr)
{
mRes = sq_throwerror(vm, "Unable to retrieve the value");
}
}
}
// ------------------------------------------------------------------------------------------------
StackStrF::~StackStrF()
{
if (mVM && !sq_isnull(mObj))
{
sq_release(mVM, &mObj);
}
}
// ------------------------------------------------------------------------------------------------
Object BufferToStrObj(const Buffer & b)
{
// Obtain the initial stack size
const StackGuard sg(DefaultVM::Get());
// Push the string onto the stack
sq_pushstring(DefaultVM::Get(), b.Data(), b.Position());
// Obtain the object from the stack and return it
return Var< Object >(DefaultVM::Get(), -1).value;
}
// --------------------------------------------------------------------------------------------
Object BufferToStrObj(const Buffer & b, Uint32 size)
{
// Perform a range check on the specified buffer
if (size > b.Capacity())
{
STHROWF("The specified buffer size is out of range: %u >= %u", size, b.Capacity());
}
// Obtain the initial stack size
const StackGuard sg(DefaultVM::Get());
// Push the string onto the stack
sq_pushstring(DefaultVM::Get(), b.Data(), size);
// Obtain the object from the stack and return it
return Var< Object >(DefaultVM::Get(), -1).value;
}
// ------------------------------------------------------------------------------------------------
} // Namespace:: SqMod

View File

@ -1,172 +0,0 @@
#ifndef _BASE_STACK_HPP_
#define _BASE_STACK_HPP_
// ------------------------------------------------------------------------------------------------
#include "SqBase.hpp"
// ------------------------------------------------------------------------------------------------
#include <sqrat.h>
// ------------------------------------------------------------------------------------------------
namespace SqMod {
/* ------------------------------------------------------------------------------------------------
* Attempt to pop the value at the specified index on the stack as a native integer.
*/
SQInteger PopStackInteger(HSQUIRRELVM vm, SQInteger idx);
/* ------------------------------------------------------------------------------------------------
* Attempt to pop the value at the specified index on the stack as a native float.
*/
SQFloat PopStackFloat(HSQUIRRELVM vm, SQInteger idx);
/* ------------------------------------------------------------------------------------------------
* Attempt to pop the value at the specified index on the stack as a signed long integer.
*/
Int64 PopStackLong(HSQUIRRELVM vm, SQInteger idx);
/* ------------------------------------------------------------------------------------------------
* Attempt to pop the value at the specified index on the stack as an unsigned long integer.
*/
Uint64 PopStackULong(HSQUIRRELVM vm, SQInteger idx);
/* ------------------------------------------------------------------------------------------------
* Create a script string object from a buffer.
*/
Object BufferToStrObj(const Buffer & b);
/* ------------------------------------------------------------------------------------------------
* Create a script string object from a portion of a buffer.
*/
Object BufferToStrObj(const Buffer & b, Uint32 size);
/* ------------------------------------------------------------------------------------------------
* Implements RAII to restore the VM stack to it's initial size on function exit.
*/
struct StackGuard
{
/* --------------------------------------------------------------------------------------------
* Default constructor.
*/
StackGuard()
: m_VM(DefaultVM::Get()), m_Top(sq_gettop(m_VM))
{
/* ... */
}
/* --------------------------------------------------------------------------------------------
* Base constructor.
*/
StackGuard(HSQUIRRELVM vm)
: m_VM(vm), m_Top(sq_gettop(vm))
{
/* ... */
}
/* --------------------------------------------------------------------------------------------
* Copy constructor. (disabled)
*/
StackGuard(const StackGuard &) = delete;
/* --------------------------------------------------------------------------------------------
* Move constructor. (disabled)
*/
StackGuard(StackGuard &&) = delete;
/* --------------------------------------------------------------------------------------------
* Destructor.
*/
~StackGuard()
{
sq_pop(m_VM, sq_gettop(m_VM) - m_Top);
}
/* --------------------------------------------------------------------------------------------
* Copy assignment operator. (disabled)
*/
StackGuard & operator = (const StackGuard &) = delete;
/* --------------------------------------------------------------------------------------------
* Move assignment operator. (disabled)
*/
StackGuard & operator = (StackGuard &&) = delete;
private:
// --------------------------------------------------------------------------------------------
HSQUIRRELVM m_VM; // The VM where the stack should be restored.
Int32 m_Top; // The top of the stack when this instance was created.
};
/* ------------------------------------------------------------------------------------------------
* Helper structure for retrieving a value from the stack as a string or a formatted string.
*/
struct StackStrF
{
// --------------------------------------------------------------------------------------------
CSStr mPtr; // Pointer to the C string that was retrieved.
SQInteger mLen; // The string length if it could be retrieved.
SQRESULT mRes; // The result of the retrieval attempts.
HSQOBJECT mObj; // Strong reference to the string object.
HSQUIRRELVM mVM; // The associated virtual machine.
/* --------------------------------------------------------------------------------------------
* Base constructor.
*/
StackStrF(HSQUIRRELVM vm, SQInteger idx, bool fmt = true);
/* --------------------------------------------------------------------------------------------
* Copy constructor. (disabled)
*/
StackStrF(const StackStrF & o) = delete;
/* --------------------------------------------------------------------------------------------
* Copy constructor. (disabled)
*/
StackStrF(StackStrF && o) = delete;
/* --------------------------------------------------------------------------------------------
* Destructor.
*/
~StackStrF();
/* --------------------------------------------------------------------------------------------
* Copy constructor. (disabled)
*/
StackStrF & operator = (const StackStrF & o) = delete;
/* --------------------------------------------------------------------------------------------
* Copy constructor. (disabled)
*/
StackStrF & operator = (StackStrF && o) = delete;
};
/* ------------------------------------------------------------------------------------------------
* Create a script object from the specified value on the default VM.
*/
template < typename T > Object MakeObject(const T & v)
{
// Remember the current stack size
const StackGuard sg;
// Transform the specified value into a script object
PushVar< T >(DefaultVM::Get(), v);
// Get the object from the stack and return it
return Var< Object >(DefaultVM::Get(), -1).value;
}
/* ------------------------------------------------------------------------------------------------
* Create a script object from the specified value on the specified VM.
*/
template < typename T > Object MakeObject(HSQUIRRELVM vm, const T & v)
{
// Remember the current stack size
const StackGuard sg;
// Transform the specified value into a script object
PushVar< T >(vm, v);
// Get the object from the stack and return it
return Var< Object >(vm, -1).value;
}
} // Namespace:: SqMod
#endif // _BASE_STACK_HPP_

View File

@ -429,11 +429,11 @@ void Register_Vector2(HSQUIRRELVM vm)
.Var(_SC("Y"), &Vector2::y)
// Properties
.Prop(_SC("Abs"), &Vector2::Abs)
// Core Metamethods
// Core Meta-methods
.Func(_SC("_tostring"), &Vector2::ToString)
.SquirrelFunc(_SC("_typename"), &Vector2::Typename)
.Func(_SC("_cmp"), &Vector2::Cmp)
// Metamethods
// Meta-methods
.Func< Vector2 (Vector2::*)(const Vector2 &) const >(_SC("_add"), &Vector2::operator +)
.Func< Vector2 (Vector2::*)(const Vector2 &) const >(_SC("_sub"), &Vector2::operator -)
.Func< Vector2 (Vector2::*)(const Vector2 &) const >(_SC("_mul"), &Vector2::operator *)

View File

@ -555,11 +555,11 @@ void Register_Vector2i(HSQUIRRELVM vm)
.Var(_SC("Y"), &Vector2i::y)
// Properties
.Prop(_SC("Abs"), &Vector2i::Abs)
// Core Metamethods
// Core Meta-methods
.Func(_SC("_tostring"), &Vector2i::ToString)
.SquirrelFunc(_SC("_typename"), &Vector2i::Typename)
.Func(_SC("_cmp"), &Vector2i::Cmp)
// Metamethods
// Meta-methods
.Func< Vector2i (Vector2i::*)(const Vector2i &) const >(_SC("_add"), &Vector2i::operator +)
.Func< Vector2i (Vector2i::*)(const Vector2i &) const >(_SC("_sub"), &Vector2i::operator -)
.Func< Vector2i (Vector2i::*)(const Vector2i &) const >(_SC("_mul"), &Vector2i::operator *)

View File

@ -464,11 +464,11 @@ void Register_Vector3(HSQUIRRELVM vm)
.Var(_SC("Z"), &Vector3::z)
// Properties
.Prop(_SC("Abs"), &Vector3::Abs)
// Core Metamethods
// Core Meta-methods
.Func(_SC("_tostring"), &Vector3::ToString)
.SquirrelFunc(_SC("_typename"), &Vector3::Typename)
.Func(_SC("_cmp"), &Vector3::Cmp)
// Metamethods
// Meta-methods
.Func< Vector3 (Vector3::*)(const Vector3 &) const >(_SC("_add"), &Vector3::operator +)
.Func< Vector3 (Vector3::*)(const Vector3 &) const >(_SC("_sub"), &Vector3::operator -)
.Func< Vector3 (Vector3::*)(const Vector3 &) const >(_SC("_mul"), &Vector3::operator *)

View File

@ -513,11 +513,11 @@ void Register_Vector4(HSQUIRRELVM vm)
.Var(_SC("w"), &Vector4::w)
// Properties
.Prop(_SC("Abs"), &Vector4::Abs)
// Core Metamethods
// Core Meta-methods
.Func(_SC("_tostring"), &Vector4::ToString)
.SquirrelFunc(_SC("_typename"), &Vector4::Typename)
.Func(_SC("_cmp"), &Vector4::Cmp)
// Metamethods
// Meta-methods
.Func< Vector4 (Vector4::*)(const Vector4 &) const >(_SC("_add"), &Vector4::operator +)
.Func< Vector4 (Vector4::*)(const Vector4 &) const >(_SC("_sub"), &Vector4::operator -)
.Func< Vector4 (Vector4::*)(const Vector4 &) const >(_SC("_mul"), &Vector4::operator *)