From 45520e31c73ca62a94f9a8441c4896cbcbd42083 Mon Sep 17 00:00:00 2001 From: LunaTheFoxgirl Date: Sat, 1 Jun 2024 15:10:32 +0200 Subject: [PATCH] Allow nstring to be used in map --- source/numem/mem/string.d | 35 +++++++++++++++++++++++++++++++---- source/numem/mem/vector.d | 16 ++++++++++++---- 2 files changed, 43 insertions(+), 8 deletions(-) diff --git a/source/numem/mem/string.d b/source/numem/mem/string.d index b65bf63..f3dc579 100644 --- a/source/numem/mem/string.d +++ b/source/numem/mem/string.d @@ -103,7 +103,7 @@ public: */ @trusted pragma(inline, true) - size_t size() { + size_t size() inout { size_t sz = this.vec_.size(); return sz > 0 ? sz-1 : sz; } @@ -112,7 +112,7 @@ public: Gets the length of the string */ @trusted - size_t length() { + size_t length() inout { return size(); } @@ -120,7 +120,7 @@ public: Gets the capacity of the string */ @trusted - size_t capacity() { + size_t capacity() inout { return this.vec_.capacity(); } @@ -153,7 +153,7 @@ public: Whether the string is empty. */ @trusted - bool empty() { + bool empty() inout { return size > 0; } @@ -165,6 +165,13 @@ public: vec_.shrinkToFit(); } + /** + Returns C string + */ + inout(T)* toCStringi() inout { + return cast(inout(T)*)this.vec_.idata(); + } + /** Returns C string */ @@ -316,6 +323,17 @@ public: return this.size == other.length && this[0..$-1] == other[0..$]; } + /** + Allows comparing strings + */ + @trusted + int opCmp(S)(ref inout S s) inout if (is(S : basic_string!T)) { + import core.stdc.string : strncmp; + if (s.size() < this.size()) return -1; + if (s.size() > this.size()) return 1; + return strncmp(this.toCStringIO(), s.toCStringIO(), this.size()); + } + /** To D string */ @@ -359,4 +377,13 @@ unittest { ndstring wd; wd.appendCString("ho"d.ptr); assert(wd.toDString() == "ho"d); +} + +@("string in map") +unittest { + import numem.mem.map : map; + map!(nstring, int) kv; + kv[nstring("uwu")] = 42; + + assert(kv[nstring("uwu")] == 42); } \ No newline at end of file diff --git a/source/numem/mem/vector.d b/source/numem/mem/vector.d index 8cf3580..0728eb4 100644 --- a/source/numem/mem/vector.d +++ b/source/numem/mem/vector.d @@ -157,6 +157,14 @@ public: return memory; } + /** + Gets the C data pointer as an inout pointer + */ + @trusted + inout(T)* idata() inout { + return cast(inout(T)*)memory; + } + /** Gets the C data pointer atomically */ @@ -213,7 +221,7 @@ public: Gets whether the vector is empty. */ @trusted - bool empty() { + bool empty() inout { return size_ == 0; } @@ -221,7 +229,7 @@ public: Gets the amount of elements in the vector */ @trusted - size_t size() { + size_t size() inout { return size_; } @@ -229,7 +237,7 @@ public: Gets the capacity of the vector */ @trusted - size_t capacity() { + size_t capacity() inout { return capacity_; } @@ -237,7 +245,7 @@ public: Returns the memory usage of the vector in bytes. */ @trusted - size_t usage() { + size_t usage() inout { return capacity_*T.sizeof; }