diff options
| author | jsmall-nvidia <jsmall@nvidia.com> | 2019-04-29 17:03:46 -0400 |
|---|---|---|
| committer | Tim Foley <tfoleyNV@users.noreply.github.com> | 2019-04-29 14:03:46 -0700 |
| commit | 4880789e3003441732cca4471091563f36531635 (patch) | |
| tree | 8e0d3ed58a561373b35729d24787afe6b39732e3 /source/core | |
| parent | ded340beb4b5197b559626acc39920abb2d39e77 (diff) | |
String/List closer to conventions, and use Index type (#959)
* List made members m_
Tweaked types to closer match conventions.
* Use asserts for checking conditions on List.
Other small improvements.
* List<T>.Count() -> getSize()
* List<T>
Add -> add
First -> getFirst
Last -> getLast
RemoveLast -> removeLast
ReleaseBuffer -> detachBuffer
GetArrayView -> getArrayView
* List<T>::
AddRange -> addRange
Capacity -> getCapacity
Insert -> insert
InsertRange -> insertRange
AddRange -> addRange
RemoveRange -> removeRange
RemoveAt -> removeAt
Remove -> remove
Reverse -> reverse
FastRemove -> fastRemove
FastRemoveAt -> fastRemoveAt
Clear -> clear
* List<T>
FreeBuffer -> _deallocateBuffer
Free -> clearAndDeallocate
SwapWith -> swapWith
* List<T>
SetSize -> setSize
Reserve -> reserve
GrowToSize growToSize
* UnsafeShrinkToSize -> unsafeShrinkToSize
Compress -> compress
FindLast -> findLastIndex
FindLast -> findLastIndex
Simplify Contains
* List<T>
Removed m_allocator (wasn't used)
Swap -> swapElements
Sort -> sort
Contains -> contains
ForEach -> forEach
QuickSort -> quickSort
InsertionSort -> insertionSort
BinarySearch -> binarySearch
Max -> calcMax
Min -> calcMin
* Initializer::Initialize -> initialize
List<T>::
Allocate -> _allocate
Init -> _init
IndexOf -> indexOf
* * Put #include <assert.h> in common.h, and remove unneeded inclusions
* Small refactor of ArrayView - remove stride as not used
* getSize -> getCount
setSize -> setCount
unsafeShrinkToSize->unsafeShrinkToCount
growToSize -> growToCount
m_size -> m_count
* Some tidy up around Allocator.
* Use Index type on List.
* Refactor of IntSet.
First tentative look at using Index.
* Made Index an Int
Did preliminary fixes.
Made String use Index.
* Partial refactor of String.
* String::Buffer -> getBuffer
ToWString -> toWString
* Small improvements to String.
String::
Buffer() -> getBuffer()
Equals() -> equals
* Try to use Index where appropriate.
* Fix warnings on windows x86 builds.
Diffstat (limited to 'source/core')
30 files changed, 886 insertions, 903 deletions
diff --git a/source/core/allocator.h b/source/core/allocator.h index 3306d3780..5832d0b84 100644 --- a/source/core/allocator.h +++ b/source/core/allocator.h @@ -8,7 +8,7 @@ namespace Slang { - inline void * AlignedAlloc(size_t size, size_t alignment) + inline void* alignedAllocate(size_t size, size_t alignment) { #ifdef _MSC_VER return _aligned_malloc(size, alignment); @@ -23,7 +23,7 @@ namespace Slang #endif } - inline void AlignedFree(void * ptr) + inline void alignedDeallocate(void* ptr) { #ifdef _MSC_VER _aligned_free(ptr); @@ -36,29 +36,29 @@ namespace Slang { public: // not really called - void * Alloc(size_t size) + void* allocate(size_t size) { - return malloc(size); + return ::malloc(size); } - void Free(void * ptr) + void deallocate(void * ptr) { - return free(ptr); + return ::free(ptr); } }; - template<int alignment> + template<int ALIGNMENT> class AlignedAllocator { public: - void * Alloc(size_t size) + void* allocate(size_t size) { - return AlignedAlloc(size, alignment); + return alignedAllocate(size, ALIGNMENT); } - void Free(void * ptr) + void deallocate(void * ptr) { - return AlignedFree(ptr); + return alignedDeallocate(ptr); } }; } -#endif
\ No newline at end of file +#endif diff --git a/source/core/array-view.h b/source/core/array-view.h index 193aedbbb..ad9673e2e 100644 --- a/source/core/array-view.h +++ b/source/core/array-view.h @@ -1,7 +1,7 @@ #ifndef CORE_LIB_ARRAY_VIEW_H #define CORE_LIB_ARRAY_VIEW_H -#include "exception.h" +#include "common.h" namespace Slang { @@ -9,104 +9,87 @@ namespace Slang class ArrayView { private: - T * _buffer; - int _count; - int stride; + T* m_buffer; + int m_count; public: - T* begin() const - { - return _buffer; - } - T* end() const - { - return (T*)((char*)_buffer + _count*stride); - } + const T* begin() const { return m_buffer; } + T* begin() { return m_buffer; } + + const T* end() const { return m_buffer + m_count; } + T* end() { return m_buffer + m_count; } + public: - ArrayView() - { - _buffer = 0; - _count = 0; - } - ArrayView(const T & singleObj) - { - SetData((T*)&singleObj, 1, sizeof(T)); - } - ArrayView(T * buffer, int count) - { - SetData(buffer, count, sizeof(T)); + ArrayView(): + m_buffer(nullptr), + m_count(0) + { } - ArrayView(void * buffer, int count, int _stride) - { - SetData(buffer, count, _stride); - } - void SetData(void * buffer, int count, int _stride) - { - this->_buffer = (T*)buffer; - this->_count = count; - this->stride = _stride; - } - inline int GetCapacity() const - { - return _count; + ArrayView(T& singleObj): + m_buffer(&singleObj), + m_count(1) + { } - inline int Count() const + ArrayView(T* buffer, int size): + m_buffer(buffer), + m_count(size) { - return _count; } + + inline int getCount() const { return m_count; } - inline T & operator [](int id) const + inline const T& operator [](int idx) const { -#if _DEBUG - if (id >= _count || id < 0) - throw IndexOutofRangeException("Operator[]: Index out of Range."); -#endif - return *(T*)((char*)_buffer+id*stride); + SLANG_ASSERT(idx >= 0 && idx <= m_count); + return m_buffer[idx]; } + inline T& operator [](int idx) + { + SLANG_ASSERT(idx >= 0 && idx <= m_count); + return m_buffer[idx]; + } - inline T* Buffer() const - { - return _buffer; - } + inline const T* getBuffer() const { return m_buffer; } + inline T* getBuffer() { return m_buffer; } template<typename T2> - int IndexOf(const T2 & val) const + int indexOf(const T2 & val) const { - for (int i = 0; i < _count; i++) + for (int i = 0; i < m_count; i++) { - if (*(T*)((char*)_buffer + i*stride) == val) + if (m_buffer[i] == val) return i; } return -1; } template<typename T2> - int LastIndexOf(const T2 & val) const + int lastIndexOf(const T2 & val) const { - for (int i = _count - 1; i >= 0; i--) + for (int i = m_count - 1; i >= 0; i--) { - if (*(T*)((char*)_buffer + i*stride) == val) + if (m_buffer[i] == val) return i; } return -1; } template<typename Func> - int FindFirst(const Func & predicate) const + int findFirstIndex(const Func& predicate) const { - for (int i = 0; i < _count; i++) + for (int i = 0; i < m_count; i++) { - if (predicate(_buffer[i])) + if (predicate(m_buffer[i])) return i; } return -1; } template<typename Func> - int FindLast(const Func & predicate) const + int findLastIndex(const Func& predicate) const { - for (int i = _count - 1; i >= 0; i--) + for (int i = m_count - 1; i >= 0; i--) { - if (predicate(_buffer[i])) + if (predicate(m_buffer[i])) return i; } return -1; @@ -114,16 +97,16 @@ namespace Slang }; template<typename T> - ArrayView<T> MakeArrayView(const T & obj) + ArrayView<T> makeArrayView(T& obj) { return ArrayView<T>(obj); } template<typename T> - ArrayView<T> MakeArrayView(T * buffer, int count) + ArrayView<T> makeArrayView(T* buffer, int count) { return ArrayView<T>(buffer, count); } } -#endif
\ No newline at end of file +#endif diff --git a/source/core/array.h b/source/core/array.h index 96508879f..2a5fa0aa7 100644 --- a/source/core/array.h +++ b/source/core/array.h @@ -6,138 +6,130 @@ namespace Slang { - template<typename T, int size> + template<typename T, int COUNT> class Array { private: - T _buffer[size]; - int _count = 0; + T m_buffer[COUNT]; + int m_count = 0; public: - T* begin() const - { - return (T*)_buffer; - } - T* end() const - { - return (T*)_buffer + _count; - } + T* begin() { return m_buffer; } + const T* begin() const { return m_buffer; } + + const T* end() const { return m_buffer + m_count; } + T* end() { return m_buffer + m_count; } + public: - inline int GetCapacity() const + inline int getCapacity() const { return COUNT; } + inline int getCount() const { return m_count; } + inline const T& getFirst() const { - return size; + SLANG_ASSERT(m_count > 0); + return m_buffer[0]; } - inline int Count() const + inline T& getFirst() + { + SLANG_ASSERT(m_count > 0); + return m_buffer[0]; + } + inline const T& getLast() const { - return _count; + SLANG_ASSERT(m_count > 0); + return m_buffer[m_count - 1]; } - inline T & First() const + inline T& getLast() + { + SLANG_ASSERT(m_count > 0); + return m_buffer[m_count - 1]; + } + inline void setCount(int newCount) { - return const_cast<T&>(_buffer[0]); + SLANG_ASSERT(newCount >= 0 && newCount <= COUNT); + m_count = newCount; } - inline T & Last() const + inline void add(const T & item) { - return const_cast<T&>(_buffer[_count - 1]); + SLANG_ASSERT(m_count < COUNT); + m_buffer[m_count++] = item; } - inline void SetSize(int newSize) + inline void add(T && item) { -#ifdef _DEBUG - if (newSize > size) - throw IndexOutofRangeException("size too large."); -#endif - _count = newSize; - } - inline void Add(const T & item) - { -#ifdef _DEBUG - if (_count == size) - throw IndexOutofRangeException("out of range access to static array."); -#endif - _buffer[_count++] = item; - } - inline void Add(T && item) - { -#ifdef _DEBUG - if (_count == size) - throw IndexOutofRangeException("out of range access to static array."); -#endif - _buffer[_count++] = _Move(item); + SLANG_ASSERT(m_count < COUNT); + m_buffer[m_count++] = _Move(item); } - inline T & operator [](int id) const + inline const T& operator [](int idx) const { -#if _DEBUG - if (id >= _count || id < 0) - throw IndexOutofRangeException("Operator[]: Index out of Range."); -#endif - return ((T*)_buffer)[id]; + SLANG_ASSERT(idx >= 0 && idx < m_count); + return m_buffer[idx]; } + inline T& operator [](int idx) + { + SLANG_ASSERT(idx >= 0 && idx < m_count); + return m_buffer[idx]; + } - inline T* Buffer() const - { - return (T*)_buffer; - } + inline const T* getBuffer() const { return m_buffer; } + inline T* getBuffer() { return m_buffer; } - inline void Clear() - { - _count = 0; - } + inline void clear() { m_count = 0; } template<typename T2> - int IndexOf(const T2 & val) const + int indexOf(const T2& val) const { - for (int i = 0; i < _count; i++) + for (int i = 0; i < m_count; i++) { - if (_buffer[i] == val) + if (m_buffer[i] == val) return i; } return -1; } template<typename T2> - int LastIndexOf(const T2 & val) const + int lastIndexOf(const T2& val) const { - for (int i = _count - 1; i >= 0; i--) + for (int i = m_count - 1; i >= 0; i--) { - if (_buffer[i] == val) + if (m_buffer[i] == val) return i; } return -1; } - inline ArrayView<T> GetArrayView() const + inline ArrayView<T> getArrayView() const { - return ArrayView<T>((T*)_buffer, _count); + return ArrayView<T>((T*)m_buffer, m_count); } - inline ArrayView<T> GetArrayView(int start, int count) const + inline ArrayView<T> getArrayView(int start, int count) const { - return ArrayView<T>((T*)_buffer + start, count); + return ArrayView<T>((T*)m_buffer + start, count); } }; template<typename T, typename ...TArgs> struct FirstType { - typedef T type; + typedef T Type; }; - template<typename T, int size> - void InsertArray(Array<T, size> &) {} + template<typename T, int SIZE> + void insertArray(Array<T, SIZE>&) {} - template<typename T, typename ...TArgs, int size> - void InsertArray(Array<T, size> & arr, const T & val, TArgs... args) + template<typename T, typename ...TArgs, int SIZE> + void insertArray(Array<T, SIZE>& arr, const T& val, TArgs... args) { - arr.Add(val); - InsertArray(arr, args...); + arr.add(val); + insertArray(arr, args...); } template<typename ...TArgs> - auto MakeArray(TArgs ...args) -> Array<typename FirstType<TArgs...>::type, sizeof...(args)> + auto makeArray(TArgs ...args) -> Array<typename FirstType<TArgs...>::Type, sizeof...(args)> { - Array<typename FirstType<TArgs...>::type, sizeof...(args)> rs; - InsertArray(rs, args...); + Array<typename FirstType<TArgs...>::Type, sizeof...(args)> rs; + insertArray(rs, args...); return rs; } } -#endif
\ No newline at end of file +#endif diff --git a/source/core/common.h b/source/core/common.h index ba7cd9836..0e5396caf 100644 --- a/source/core/common.h +++ b/source/core/common.h @@ -3,6 +3,8 @@ #include "../../slang.h" +#include <assert.h> + #include <cstdint> #ifdef __GNUC__ @@ -29,6 +31,9 @@ namespace Slang typedef intptr_t PtrInt; + // Type used for indexing, in arrays/views etc + typedef Int Index; + template <typename T> inline T&& _Move(T & obj) { diff --git a/source/core/dictionary.h b/source/core/dictionary.h index 6d97bc2b3..a38699368 100644 --- a/source/core/dictionary.h +++ b/source/core/dictionary.h @@ -91,25 +91,25 @@ namespace Slang } inline bool IsDeleted(int pos) const { - return marks.Contains((pos << 1) + 1); + return marks.contains((pos << 1) + 1); } inline bool IsEmpty(int pos) const { - return !marks.Contains((pos << 1)); + return !marks.contains((pos << 1)); } inline void SetDeleted(int pos, bool val) { if (val) - marks.Add((pos << 1) + 1); + marks.add((pos << 1) + 1); else - marks.Remove((pos << 1) + 1); + marks.remove((pos << 1) + 1); } inline void SetEmpty(int pos, bool val) { if (val) - marks.Remove((pos << 1)); + marks.remove((pos << 1)); else - marks.Add((pos << 1)); + marks.add((pos << 1)); } struct FindPositionResult { @@ -180,7 +180,7 @@ namespace Slang Dictionary<TKey, TValue> newDict; newDict.bucketSizeMinusOne = newSize - 1; newDict.hashMap = new KeyValuePair<TKey, TValue>[newSize]; - newDict.marks.SetMax(newSize * 2); + newDict.marks.setMax(newSize * 2); if (hashMap) { for (auto & kvPair : *this) @@ -326,7 +326,7 @@ namespace Slang { _count = 0; - marks.Clear(); + marks.clear(); } TValue* TryGetValueOrAdd(const TKey& key, const TValue& value) diff --git a/source/core/int-set.h b/source/core/int-set.h index 6b6f5e7a8..6b6243552 100644 --- a/source/core/int-set.h +++ b/source/core/int-set.h @@ -10,154 +10,200 @@ namespace Slang { + /* The set works by storing as a bit per integer */ class IntSet { private: - List<int> buffer; + typedef uint32_t Element; ///< Type that holds the bits + enum + { + ELEMENT_SHIFT = 5, ///< How many bits to shift to get Element index from an index + ELEMENT_SIZE = sizeof(Element) * 8, ///< The number of bits in an element + ELEMENT_MASK = ELEMENT_SIZE - 1, ///< Mask to get shift from an index + }; + + // Make sure they are correct for the Element type + SLANG_COMPILE_TIME_ASSERT( (1 << ELEMENT_SHIFT) == ELEMENT_SIZE); + + List<Element> m_buffer; + public: IntSet() {} - IntSet(const IntSet & other) + IntSet(const IntSet& other) { - buffer = other.buffer; + m_buffer = other.m_buffer; } IntSet(IntSet && other) { *this = (_Move(other)); } - IntSet & operator = (IntSet && other) + IntSet& operator=(IntSet&& other) { - buffer = _Move(other.buffer); + m_buffer = _Move(other.m_buffer); return *this; } - IntSet & operator = (const IntSet & other) + IntSet& operator=(const IntSet& other) { - buffer = other.buffer; + m_buffer = other.m_buffer; return *this; } int GetHashCode() { int rs = 0; - for (auto val : buffer) + for (auto val : m_buffer) rs ^= val; return rs; } - IntSet(int maxVal) + IntSet(Int maxVal) { - SetMax(maxVal); + setMax(maxVal); } - UInt Size() const + Int getCount() const { - return buffer.Count()*32; + return Int(m_buffer.getCount()) * ELEMENT_SIZE; } - void SetMax(int val) + void setMax(Int val) { - Resize(val); - Clear(); + resize(val); + clear(); } - void SetAll() + void setAll() { - for (UInt i = 0; i<buffer.Count(); i++) - buffer[i] = 0xFFFFFFFF; + for (Index i = 0; i < m_buffer.getCount(); i++) + m_buffer[i] = ~Element(0); } - void Resize(UInt size) + void resize(Int size) { - UInt oldBufferSize = buffer.Count(); - buffer.SetSize((size+31)>>5); - if (buffer.Count() > oldBufferSize) - memset(buffer.Buffer()+oldBufferSize, 0, (buffer.Count()-oldBufferSize) * sizeof(int)); + const Index oldBufferSize = m_buffer.getCount(); + const Index newCount = Index((size + ELEMENT_MASK) >> ELEMENT_SHIFT); + m_buffer.setCount(newCount); + + if (newCount > oldBufferSize) + memset(m_buffer.getBuffer() + oldBufferSize, 0, (newCount - oldBufferSize) * sizeof(Element)); } - void Clear() + void clear() { - for (UInt i = 0; i<buffer.Count(); i++) - buffer[i] = 0; + for (Index i = 0; i < m_buffer.getCount(); i++) + m_buffer[i] = 0; } - void Add(UInt val) + void clearAndDeallocate() + { + m_buffer.clearAndDeallocate(); + } + void add(Int val) { - UInt id = val>>5; - if (id < buffer.Count()) - buffer[id] |= (1<<(val&31)); + Index id = Index(val >> 5); + if (id < m_buffer.getCount()) + m_buffer[id] |= Element(1) << (val & ELEMENT_MASK); else { - UInt oldSize = buffer.Count(); - buffer.SetSize(id+1); - memset(buffer.Buffer() + oldSize, 0, (buffer.Count()-oldSize)*sizeof(int)); - buffer[id] |= (1<<(val&31)); + Index oldCount = m_buffer.getCount(); + m_buffer.setCount(id + 1); + memset(m_buffer.getBuffer() + oldCount, 0, (m_buffer.getCount() - oldCount) * sizeof(Element)); + m_buffer[id] |= Element(1) << (val & ELEMENT_MASK); } } - void Remove(UInt val) + void remove(Int val) { - if ((val>>5) < buffer.Count()) - buffer[(val>>5)] &= ~(1<<(val&31)); + const Index idx = Index(val >> ELEMENT_SHIFT); + if (idx < m_buffer.getCount()) + m_buffer[idx] &= ~(Element(1) << (val & ELEMENT_MASK)); } - bool Contains(UInt val) const + bool contains(Int val) const { - if ((val>>5) >= buffer.Count()) + const Index idx = Index(val >> ELEMENT_SHIFT); + if (idx >= m_buffer.getCount()) return false; - return (buffer[(val>>5)] & (1<<(val&31))) != 0; + return (m_buffer[idx] & (Element(1) << (val & ELEMENT_MASK))) != 0; } - void UnionWith(const IntSet & set) + void unionWith(const IntSet& set) { - for (UInt i = 0; i<Math::Min(set.buffer.Count(), buffer.Count()); i++) + const Index minCount = Math::Min(set.m_buffer.getCount(), m_buffer.getCount()); + for (Index i = 0; i < minCount; i++) { - buffer[i] |= set.buffer[i]; + m_buffer[i] |= set.m_buffer[i]; } - if (set.buffer.Count() > buffer.Count()) - buffer.AddRange(set.buffer.Buffer()+buffer.Count(), set.buffer.Count()-buffer.Count()); + if (set.m_buffer.getCount() > m_buffer.getCount()) + m_buffer.addRange(set.m_buffer.getBuffer()+m_buffer.getCount(), set.m_buffer.getCount()-m_buffer.getCount()); } - bool operator == (const IntSet & set) + bool operator==(const IntSet& set) const { - if (buffer.Count() != set.buffer.Count()) - return false; - for (UInt i = 0; i<buffer.Count(); i++) - if (buffer[i] != set.buffer[i]) - return false; - return true; + Index minCount = Math::Min(set.m_buffer.getCount(), m_buffer.getCount()); + if (::memcmp(m_buffer.getBuffer(), set.m_buffer.getBuffer(), minCount * sizeof(Element)) != 0) + { + return false; + } + return m_buffer.getCount() == set.m_buffer.getCount() || (_areRemainingZeros(m_buffer, minCount) && _areRemainingZeros(set.m_buffer, minCount)); } - bool operator != (const IntSet & set) + bool operator!=(const IntSet& set) const { return !(*this == set); } - void IntersectWith(const IntSet & set) + void intersectWith(const IntSet& set) { - if (set.buffer.Count() < buffer.Count()) - memset(buffer.Buffer() + set.buffer.Count(), 0, (buffer.Count()-set.buffer.Count())*sizeof(int)); - for (UInt i = 0; i<Math::Min(set.buffer.Count(), buffer.Count()); i++) + if (set.m_buffer.getCount() < m_buffer.getCount()) + memset(m_buffer.getBuffer() + set.m_buffer.getCount(), 0, (m_buffer.getCount() - set.m_buffer.getCount()) * sizeof(Element)); + + const Index minCount = Math::Min(set.m_buffer.getCount(), m_buffer.getCount()); + for (Index i = 0; i < minCount; i++) { - buffer[i] &= set.buffer[i]; + m_buffer[i] &= set.m_buffer[i]; } } - static void Union(IntSet & rs, const IntSet & set1, const IntSet & set2) + static void calcUnion(IntSet& outRs, const IntSet& set1, const IntSet& set2) { - rs.buffer.SetSize(Math::Max(set1.buffer.Count(), set2.buffer.Count())); - rs.Clear(); - for (UInt i = 0; i<set1.buffer.Count(); i++) - rs.buffer[i] |= set1.buffer[i]; - for (UInt i = 0; i<set2.buffer.Count(); i++) - rs.buffer[i] |= set2.buffer[i]; + outRs.m_buffer.setCount(Math::Max(set1.m_buffer.getCount(), set2.m_buffer.getCount())); + outRs.clear(); + for (Index i = 0; i < set1.m_buffer.getCount(); i++) + outRs.m_buffer[i] |= set1.m_buffer[i]; + for (Index i = 0; i < set2.m_buffer.getCount(); i++) + outRs.m_buffer[i] |= set2.m_buffer[i]; } - static void Intersect(IntSet & rs, const IntSet & set1, const IntSet & set2) + static void calcIntersection(IntSet& outRs, const IntSet& set1, const IntSet& set2) { - rs.buffer.SetSize(Math::Min(set1.buffer.Count(), set2.buffer.Count())); - for (UInt i = 0; i<rs.buffer.Count(); i++) - rs.buffer[i] = set1.buffer[i] & set2.buffer[i]; + const Index minCount = Math::Min(set1.m_buffer.getCount(), set2.m_buffer.getCount()); + outRs.m_buffer.setCount(minCount); + + for (Index i = 0; i < minCount; i++) + outRs.m_buffer[i] = set1.m_buffer[i] & set2.m_buffer[i]; } - static void Subtract(IntSet & rs, const IntSet & set1, const IntSet & set2) + static void calcSubtract(IntSet& outRs, const IntSet& set1, const IntSet& set2) { - rs.buffer.SetSize(set1.buffer.Count()); - for (UInt i = 0; i<Math::Min(set1.buffer.Count(), set2.buffer.Count()); i++) - rs.buffer[i] = set1.buffer[i] & (~set2.buffer[i]); + outRs.m_buffer.setCount(set1.m_buffer.getCount()); + + const Index minCount = Math::Min(set1.m_buffer.getCount(), set2.m_buffer.getCount()); + for (Index i = 0; i < minCount; i++) + outRs.m_buffer[i] = set1.m_buffer[i] & (~set2.m_buffer[i]); } - static bool HasIntersection(const IntSet & set1, const IntSet & set2) + static bool hasIntersection(const IntSet& set1, const IntSet& set2) { - for (UInt i = 0; i<Math::Min(set1.buffer.Count(), set2.buffer.Count()); i++) + const Index minCount = Math::Min(set1.m_buffer.getCount(), set2.m_buffer.getCount()); + for (Index i = 0; i < minCount; i++) { - if (set1.buffer[i] & set2.buffer[i]) + if (set1.m_buffer[i] & set2.m_buffer[i]) return true; } return false; } + + private: + static bool _areRemainingZeros(const List<Element>& elems, Index minCount) + { + const Index count = elems.getCount(); + const Element* base = elems.getBuffer(); + + for (Index i = minCount; i < count; ++i) + { + if (base[i]) + { + return false; + } + } + return true; + } + }; } -#endif
\ No newline at end of file +#endif diff --git a/source/core/list.h b/source/core/list.h index 11d798dcf..7ba313305 100644 --- a/source/core/list.h +++ b/source/core/list.h @@ -1,4 +1,4 @@ -#ifndef FUNDAMENTAL_LIB_LIST_H +#ifndef FUNDAMENTAL_LIB_LIST_H #define FUNDAMENTAL_LIB_LIST_H #include "../../slang.h" @@ -11,10 +11,10 @@ #include <new> #include <type_traits> -const int MIN_QSORT_SIZE = 32; namespace Slang { + template<typename T, int isPOD> class Initializer { @@ -25,7 +25,7 @@ namespace Slang class Initializer<T, 0> { public: - static void Initialize(T * buffer, int size) + static void initialize(T* buffer, int size) { for (int i = 0; i<size; i++) new (buffer + i) T(); @@ -35,7 +35,7 @@ namespace Slang class Initializer<T, 1> { public: - static void Initialize(T * buffer, int size) + static void initialize(T* buffer, int size) { // It's pod so no initialization required //for (int i = 0; i < size; i++) @@ -47,22 +47,22 @@ namespace Slang class AllocateMethod { public: - static inline T* Alloc(UInt size) + static inline T* allocateArray(Index count) { TAllocator allocator; - T * rs = (T*)allocator.Alloc(size*sizeof(T)); - Initializer<T, std::is_pod<T>::value>::Initialize(rs, size); + T * rs = (T*)allocator.allocate(count * sizeof(T)); + Initializer<T, std::is_pod<T>::value>::initialize(rs, count); return rs; } - static inline void Free(T * ptr, UInt bufferSize) + static inline void deallocateArray(T* ptr, Index count) { TAllocator allocator; if (!std::is_trivially_destructible<T>::value) { - for (UInt i = 0; i<bufferSize; i++) + for (Index i = 0; i < count; i++) ptr[i].~T(); } - allocator.Free(ptr); + allocator.deallocate(ptr); } }; @@ -70,11 +70,11 @@ namespace Slang class AllocateMethod<T, StandardAllocator> { public: - static inline T* Alloc(UInt size) + static inline T* allocateArray(Index count) { - return new T[size]; + return new T[count]; } - static inline void Free(T* ptr, UInt /*bufferSize*/) + static inline void deallocateArray(T* ptr, Index /*bufferSize*/) { delete [] ptr; } @@ -84,226 +84,177 @@ namespace Slang template<typename T, typename TAllocator = StandardAllocator> class List { - private: + private: + static const Index kInitialCount = 16; - inline T * Allocate(UInt size) - { - return AllocateMethod<T, TAllocator>::Alloc(size); - - } - private: - static const int InitialSize = 16; - TAllocator allocator; - private: - T* buffer; - UInt _count; - UInt bufferSize; - void FreeBuffer() - { - AllocateMethod<T, TAllocator>::Free(buffer, bufferSize); - buffer = 0; - } - void Free() - { - if (buffer) - { - FreeBuffer(); - } - buffer = 0; - _count = bufferSize = 0; - } - public: - T* begin() const - { - return buffer; - } - T* end() const - { - return buffer+_count; - } - private: - template<typename... Args> - void Init(const T & val, Args... args) - { - Add(val); - Init(args...); - } public: List() - : buffer(0), _count(0), bufferSize(0) + : m_buffer(nullptr), m_count(0), m_capacity(0) { } template<typename... Args> - List(const T & val, Args... args) + List(const T& val, Args... args) { - Init(val, args...); + _init(val, args...); } - List(const List<T> & list) - : buffer(0), _count(0), bufferSize(0) + List(const List<T>& list) + : m_buffer(nullptr), m_count(0), m_capacity(0) { this->operator=(list); } - List(List<T> && list) - : buffer(0), _count(0), bufferSize(0) + List(List<T>&& list) + : m_buffer(nullptr), m_count(0), m_capacity(0) { this->operator=(static_cast<List<T>&&>(list)); } - static List<T> Create(const T & val, int count) + static List<T> makeRepeated(const T& val, Index count) { List<T> rs; - rs.SetSize(count); - for (int i = 0; i < count; i++) + rs.setCount(count); + for (Index i = 0; i < count; i++) rs[i] = val; return rs; } ~List() { - Free(); + _deallocateBuffer(); } - List<T> & operator=(const List<T> & list) + List<T>& operator=(const List<T>& list) { - Free(); - AddRange(list); - + clearAndDeallocate(); + addRange(list); return *this; } - List<T> & operator=(List<T> && list) + List<T>& operator=(List<T>&& list) { - Free(); - _count = list._count; - bufferSize = list.bufferSize; - buffer = list.buffer; + // Could just do a swap here, and memory would be freed on rhs dtor + + _deallocateBuffer(); + m_count = list.m_count; + m_capacity = list.m_capacity; + m_buffer = list.m_buffer; - list.buffer = 0; - list._count = 0; - list.bufferSize = 0; + list.m_buffer = nullptr; + list.m_count = 0; + list.m_capacity = 0; return *this; } - T & First() const + // TODO(JS): These should be made const safe but some other code depends on this behavior for now. + T* begin() const { return m_buffer; } + T* end() const { return m_buffer + m_count; } + + const T& getFirst() const { -#ifdef _DEBUG - if (_count == 0) - throw "Index out of range."; -#endif - return buffer[0]; + SLANG_ASSERT(m_count > 0); + return m_buffer[0]; } - T & Last() const + const T& getLast() const { -#ifdef _DEBUG - if (_count == 0) - throw "Index out of range."; -#endif - return buffer[_count-1]; + SLANG_ASSERT(m_count > 0); + return m_buffer[m_count-1]; } - void RemoveLast() + T& getFirst() + { + SLANG_ASSERT(m_count > 0); + return m_buffer[0]; + } + + T& getLast() + { + SLANG_ASSERT(m_count > 0); + return m_buffer[m_count - 1]; + } + + void removeLast() { -#ifdef _DEBUG - if (_count == 0) - throw "Index out of range."; -#endif - _count--; + SLANG_ASSERT(m_count > 0); + m_count--; } - inline void SwapWith(List<T, TAllocator> & other) + inline void swapWith(List<T, TAllocator>& other) { - T* tmpBuffer = this->buffer; - this->buffer = other.buffer; - other.buffer = tmpBuffer; - auto tmpBufferSize = this->bufferSize; - this->bufferSize = other.bufferSize; - other.bufferSize = tmpBufferSize; - auto tmpCount = this->_count; - this->_count = other._count; - other._count = tmpCount; - TAllocator tmpAlloc = _Move(this->allocator); - this->allocator = _Move(other.allocator); - other.allocator = _Move(tmpAlloc); + T* buffer = m_buffer; + m_buffer = other.m_buffer; + other.m_buffer = buffer; + + auto bufferSize = m_capacity; + m_capacity = other.m_capacity; + other.m_capacity = bufferSize; + + auto count = m_count; + m_count = other.m_count; + other.m_count = count; } - T* ReleaseBuffer() + T* detachBuffer() { - T* rs = buffer; - buffer = nullptr; - _count = 0; - bufferSize = 0; + T* rs = m_buffer; + m_buffer = nullptr; + m_count = 0; + m_capacity = 0; return rs; } - inline ArrayView<T> GetArrayView() const + inline ArrayView<T> getArrayView() const { - return ArrayView<T>(buffer, _count); + return ArrayView<T>(m_buffer, m_count); } - inline ArrayView<T> GetArrayView(int start, int count) const + inline ArrayView<T> getArrayView(Index start, Index count) const { -#ifdef _DEBUG - if (start + count > _count || start < 0 || count < 0) - throw "Index out of range."; -#endif - return ArrayView<T>(buffer + start, count); + SLANG_ASSERT(start >= 0 && count >= 0 && start + count <= m_count); + return ArrayView<T>(m_buffer + start, count); } - void Add(T && obj) + void add(T&& obj) { - if (bufferSize < _count + 1) + if (m_capacity < m_count + 1) { - UInt newBufferSize = InitialSize; - if (bufferSize) - newBufferSize = (bufferSize << 1); + Index newBufferSize = kInitialCount; + if (m_capacity) + newBufferSize = (m_capacity << 1); - Reserve(newBufferSize); + reserve(newBufferSize); } - buffer[_count++] = static_cast<T&&>(obj); + m_buffer[m_count++] = static_cast<T&&>(obj); } - void Add(const T & obj) + void add(const T& obj) { - if (bufferSize < _count + 1) + if (m_capacity < m_count + 1) { - UInt newBufferSize = InitialSize; - if (bufferSize) - newBufferSize = (bufferSize << 1); + Index newBufferSize = kInitialCount; + if (m_capacity) + newBufferSize = (m_capacity << 1); - Reserve(newBufferSize); + reserve(newBufferSize); } - buffer[_count++] = obj; + m_buffer[m_count++] = obj; } - UInt Count() const - { - return _count; - } + Index getCount() const { return m_count; } + Index getCapacity() const { return m_capacity; } - T * Buffer() const - { - return buffer; - } + const T* getBuffer() const { return m_buffer; } + T* getBuffer() { return m_buffer; } - UInt Capacity() const - { - return bufferSize; - } + void insert(Index idx, const T& val) { insertRange(idx, &val, 1); } - void Insert(UInt id, const T & val) + void insertRange(Index idx, const T* vals, Index n) { - InsertRange(id, &val, 1); - } - - void InsertRange(UInt id, const T * vals, UInt n) - { - if (bufferSize < _count + n) + if (m_capacity < m_count + n) { - UInt newBufferSize = InitialSize; - while (newBufferSize < _count + n) - newBufferSize = newBufferSize << 1; + Index newBufferCount = kInitialCount; + while (newBufferCount < m_count + n) + newBufferCount = newBufferCount << 1; - T * newBuffer = Allocate(newBufferSize); - if (bufferSize) + T* newBuffer = _allocate(newBufferCount); + if (m_capacity) { /*if (std::has_trivial_copy_assign<T>::value && std::has_trivial_destructor<T>::value) { @@ -312,15 +263,15 @@ namespace Slang } else*/ { - for (UInt i = 0; i < id; i++) - newBuffer[i] = buffer[i]; - for (UInt i = id; i < _count; i++) - newBuffer[i + n] = T(static_cast<T&&>(buffer[i])); + for (Index i = 0; i < idx; i++) + newBuffer[i] = m_buffer[i]; + for (Index i = idx; i < m_count; i++) + newBuffer[i + n] = T(static_cast<T&&>(m_buffer[i])); } - FreeBuffer(); + _deallocateBuffer(); } - buffer = newBuffer; - bufferSize = newBufferSize; + m_buffer = newBuffer; + m_capacity = newBufferCount; } else { @@ -328,17 +279,17 @@ namespace Slang memmove(buffer + id + n, buffer + id, sizeof(T) * (_count - id)); else*/ { - for (UInt i = _count; i > id; i--) - buffer[i + n - 1] = static_cast<T&&>(buffer[i - 1]); + for (Index i = m_count; i > idx; i--) + m_buffer[i + n - 1] = static_cast<T&&>(m_buffer[i - 1]); } } /*if (std::has_trivial_copy_assign<T>::value && std::has_trivial_destructor<T>::value) memcpy(buffer + id, vals, sizeof(T) * n); else*/ - for (UInt i = 0; i < n; i++) - buffer[id + i] = vals[i]; + for (Index i = 0; i < n; i++) + m_buffer[idx + i] = vals[i]; - _count += n; + m_count += n; } //slower than original edition @@ -347,261 +298,238 @@ namespace Slang // InsertRange(_count, &val, 1); //} - void InsertRange(int id, const List<T> & list) - { - InsertRange(id, list.buffer, list._count); - } + void insertRange(Index id, const List<T>& list) { insertRange(id, list.m_buffer, list.m_count); } - void AddRange(ArrayView<T> list) - { - InsertRange(_count, list.Buffer(), list.Count()); - } + void addRange(ArrayView<T> list) { insertRange(m_count, list.getBuffer(), list.Count()); } - void AddRange(const T * vals, UInt n) - { - InsertRange(_count, vals, n); - } + void addRange(const T* vals, Index n) { insertRange(m_count, vals, n); } - void AddRange(const List<T> & list) - { - InsertRange(_count, list.buffer, list._count); - } + void addRange(const List<T>& list) { insertRange(m_count, list.m_buffer, list.m_count); } - void RemoveRange(UInt id, UInt deleteCount) + void removeRange(Index idx, Index count) { -#if _DEBUG - if (id >= _count) - throw "Remove: Index out of range."; -#endif - UInt actualDeleteCount = ((id + deleteCount) >= _count)? (_count - id) : deleteCount; - for (UInt i = id + actualDeleteCount; i < _count; i++) - buffer[i - actualDeleteCount] = static_cast<T&&>(buffer[i]); - _count -= actualDeleteCount; - } + SLANG_ASSERT(idx >= 0 && idx <= m_count); - void RemoveAt(UInt id) - { - RemoveRange(id, 1); + const Index actualDeleteCount = ((idx + count) >= m_count)? (m_count - idx) : count; + for (Index i = idx + actualDeleteCount; i < m_count; i++) + m_buffer[i - actualDeleteCount] = static_cast<T&&>(m_buffer[i]); + m_count -= actualDeleteCount; } - void Remove(const T & val) + void removeAt(Index id) { removeRange(id, 1); } + + void remove(const T& val) { - int idx = IndexOf(val); + Index idx = indexOf(val); if (idx != -1) - RemoveAt(idx); + removeAt(idx); } - void Reverse() + void reverse() { - for (UInt i = 0; i < (_count >> 1); i++) + for (Index i = 0; i < (m_count >> 1); i++) { - Swap(buffer, i, _count - i - 1); + swapElements(m_buffer, i, m_count - i - 1); } } - void FastRemove(const T & val) + void fastRemove(const T& val) { - int idx = IndexOf(val); - FastRemoveAt(idx); + Index idx = indexOf(val); + fastRemoveAt(idx); } - void FastRemoveAt(UInt idx) + void fastRemoveAt(Index idx) { - if (idx != -1 && _count - 1 != idx) + if (idx != -1 && m_count - 1 != idx) { - buffer[idx] = _Move(buffer[_count - 1]); + m_buffer[idx] = _Move(m_buffer[m_count - 1]); } - _count--; + m_count--; } - void Clear() - { - _count = 0; - } + void clear() { m_count = 0; } - void Reserve(UInt size) + void clearAndDeallocate() + { + _deallocateBuffer(); + m_count = m_capacity = 0; + } + + void reserve(Index size) { - if(size > bufferSize) + if(size > m_capacity) { - T * newBuffer = Allocate(size); - if (bufferSize) + T* newBuffer = _allocate(size); + if (m_capacity) { /*if (std::has_trivial_copy_assign<T>::value && std::has_trivial_destructor<T>::value) memcpy(newBuffer, buffer, _count * sizeof(T)); else*/ { - for (UInt i = 0; i < _count; i++) - newBuffer[i] = static_cast<T&&>(buffer[i]); + for (Index i = 0; i < m_count; i++) + newBuffer[i] = static_cast<T&&>(m_buffer[i]); // Default-initialize the remaining elements - for(UInt i = _count; i < size; i++) + for(Index i = m_count; i < size; i++) { new(newBuffer + i) T(); } } - FreeBuffer(); + _deallocateBuffer(); } - buffer = newBuffer; - bufferSize = size; + m_buffer = newBuffer; + m_capacity = size; } } - void GrowToSize(UInt size) + void growToCount(Index count) { - UInt newBufferSize = UInt(1) << Math::Log2Ceil(size); - if (bufferSize < newBufferSize) + Index newBufferCount = Index(1) << Math::Log2Ceil(count); + if (m_capacity < newBufferCount) { - Reserve(newBufferSize); + reserve(newBufferCount); } - this->_count = size; + m_count = count; } - void SetSize(UInt size) + void setCount(Index count) { - Reserve(size); - _count = size; + reserve(count); + m_count = count; } - void UnsafeShrinkToSize(UInt size) - { - _count = size; - } + void unsafeShrinkToCount(Index count) { m_count = count; } - void Compress() + void compress() { - if (bufferSize > _count && _count > 0) + if (m_capacity > m_count && m_count > 0) { - T * newBuffer = Allocate(_count); - for (UInt i = 0; i < _count; i++) - newBuffer[i] = static_cast<T&&>(buffer[i]); - FreeBuffer(); - buffer = newBuffer; - bufferSize = _count; + T* newBuffer = _allocate(m_count); + for (Index i = 0; i < m_count; i++) + newBuffer[i] = static_cast<T&&>(m_buffer[i]); + + _deallocateBuffer(); + m_buffer = newBuffer; + m_capacity = m_count; } } - SLANG_FORCE_INLINE T & operator [](UInt id) const + SLANG_FORCE_INLINE T& operator [](Index idx) const { -#if _DEBUG - if(id >= _count) - throw IndexOutofRangeException("Operator[]: Index out of Range."); -#endif - return buffer[id]; + SLANG_ASSERT(idx >= 0 && idx <= m_count); + return m_buffer[idx]; } template<typename Func> - UInt FindFirst(const Func & predicate) const + Index findFirstIndex(const Func& predicate) const { - for (UInt i = 0; i < _count; i++) + for (Index i = 0; i < m_count; i++) { - if (predicate(buffer[i])) + if (predicate(m_buffer[i])) return i; } - return (UInt)-1; + return (Index)-1; } template<typename Func> - UInt FindLast(const Func & predicate) const + Index findLastIndex(const Func& predicate) const { - for (UInt i = _count; i > 0; i--) + for (Index i = m_count; i > 0; i--) { - if (predicate(buffer[i-1])) + if (predicate(m_buffer[i-1])) return i-1; } - return (UInt)-1; + return (Index)-1; } template<typename T2> - UInt IndexOf(const T2 & val) const + Index indexOf(const T2& val) const { - for (UInt i = 0; i < _count; i++) + for (Index i = 0; i < m_count; i++) { - if (buffer[i] == val) + if (m_buffer[i] == val) return i; } - return (UInt)-1; + return (Index)-1; } template<typename T2> - UInt LastIndexOf(const T2 & val) const + Index lastIndexOf(const T2& val) const { - for (int i = _count; i > 0; i--) + for (Index i = m_count; i > 0; i--) { - if(buffer[i-1] == val) + if(m_buffer[i-1] == val) return i-1; } - return (UInt)-1; + return (Index)-1; } - void Sort() + void sort() { - Sort([](T const& t1, T const& t2){return t1<t2;}); + sort([](const T& t1, const T& t2){return t1 < t2;}); } - bool Contains(const T & val) - { - for (UInt i = 0; i<_count; i++) - if (buffer[i] == val) - return true; - return false; - } + bool contains(const T& val) const { return indexOf(val) != Index(-1); } template<typename Comparer> - void Sort(Comparer compare) + void sort(Comparer compare) { - //InsertionSort(buffer, 0, _count - 1); - //QuickSort(buffer, 0, _count - 1, compare); - std::sort(buffer, buffer + _count, compare); + //insertionSort(buffer, 0, _count - 1); + //quickSort(buffer, 0, _count - 1, compare); + std::sort(m_buffer, m_buffer + m_count, compare); } template <typename IterateFunc> - void ForEach(IterateFunc f) const + void forEach(IterateFunc f) const { - for (int i = 0; i<_count; i++) - f(buffer[i]); + for (Index i = 0; i< m_count; i++) + f(m_buffer[i]); } template<typename Comparer> - void QuickSort(T * vals, int startIndex, int endIndex, Comparer comparer) + void quickSort(T* vals, Index startIndex, Index endIndex, Comparer comparer) { + static const Index kMinQSortSize = 32; + if(startIndex < endIndex) { - if (endIndex - startIndex < MIN_QSORT_SIZE) - InsertionSort(vals, startIndex, endIndex, comparer); + if (endIndex - startIndex < kMinQSortSize) + insertionSort(vals, startIndex, endIndex, comparer); else { - int pivotIndex = (startIndex + endIndex) >> 1; - int pivotNewIndex = Partition(vals, startIndex, endIndex, pivotIndex, comparer); - QuickSort(vals, startIndex, pivotNewIndex - 1, comparer); - QuickSort(vals, pivotNewIndex + 1, endIndex, comparer); + Index pivotIndex = (startIndex + endIndex) >> 1; + Index pivotNewIndex = partition(vals, startIndex, endIndex, pivotIndex, comparer); + quickSort(vals, startIndex, pivotNewIndex - 1, comparer); + quickSort(vals, pivotNewIndex + 1, endIndex, comparer); } } } template<typename Comparer> - int Partition(T * vals, int left, int right, int pivotIndex, Comparer comparer) + Index partition(T* vals, Index left, Index right, Index pivotIndex, Comparer comparer) { T pivotValue = vals[pivotIndex]; - Swap(vals, right, pivotIndex); - int storeIndex = left; - for (int i = left; i < right; i++) + swapElements(vals, right, pivotIndex); + Index storeIndex = left; + for (Index i = left; i < right; i++) { if (comparer(vals[i], pivotValue)) { - Swap(vals, i, storeIndex); + swapElements(vals, i, storeIndex); storeIndex++; } } - Swap(vals, storeIndex, right); + swapElements(vals, storeIndex, right); return storeIndex; } template<typename Comparer> - void InsertionSort(T * vals, int startIndex, int endIndex, Comparer comparer) + void insertionSort(T* vals, Index startIndex, Index endIndex, Comparer comparer) { - for (int i = startIndex + 1; i <= endIndex; i++) + for (Index i = startIndex + 1; i <= endIndex; i++) { T insertValue = static_cast<T&&>(vals[i]); - int insertIndex = i - 1; + Index insertIndex = i - 1; while (insertIndex >= startIndex && comparer(insertValue, vals[insertIndex])) { vals[insertIndex + 1] = static_cast<T&&>(vals[insertIndex]); @@ -611,7 +539,7 @@ namespace Slang } } - inline void Swap(T * vals, int index1, int index2) + inline void swapElements(T* vals, Index index1, Index index2) { if (index1 != index2) { @@ -622,13 +550,13 @@ namespace Slang } template<typename T2, typename Comparer> - int BinarySearch(const T2 & obj, Comparer comparer) + Index binarySearch(const T2& obj, Comparer comparer) { - int imin = 0, imax = _count - 1; + Index imin = 0, imax = m_count - 1; while (imax >= imin) { - int imid = (imin + imax) >> 1; - int compareResult = comparer(buffer[imid], obj); + Index imid = (imin + imax) >> 1; + int compareResult = comparer(m_buffer[imid], obj); if (compareResult == 0) return imid; else if (compareResult < 0) @@ -640,9 +568,9 @@ namespace Slang } template<typename T2> - int BinarySearch(const T2 & obj) + int binarySearch(const T2& obj) { - return BinarySearch(obj, + return binarySearch(obj, [](T & curObj, const T2 & thatObj)->int { if (curObj < thatObj) @@ -653,23 +581,47 @@ namespace Slang return 1; }); } + private: + T* m_buffer; ///< A new T[N] allocated buffer. NOTE! All elements up to capacity are in some valid form for T. + Index m_capacity; ///< The total capacity of elements + Index m_count; ///< The amount of elements + + void _deallocateBuffer() + { + if (m_buffer) + { + AllocateMethod<T, TAllocator>::deallocateArray(m_buffer, m_capacity); + m_buffer = nullptr; + } + } + static inline T* _allocate(Index count) + { + return AllocateMethod<T, TAllocator>::allocateArray(count); + } + + template<typename... Args> + void _init(const T& val, Args... args) + { + add(val); + _init(args...); + } }; template<typename T> - T Min(const List<T> & list) + T calcMin(const List<T>& list) { - T minVal = list.First(); - for (int i = 1; i<list.Count(); i++) + T minVal = list.getFirst(); + for (Index i = 1; i < list.getCount(); i++) if (list[i] < minVal) minVal = list[i]; return minVal; } template<typename T> - T Max(const List<T> & list) + T calcMax(const List<T>& list) { - T maxVal = list.First(); - for (int i = 1; i<list.Count(); i++) + T maxVal = list.getFirst(); + for (Index i = 1; i< list.getCount(); i++) if (list[i] > maxVal) maxVal = list[i]; return maxVal; diff --git a/source/core/platform.cpp b/source/core/platform.cpp index 238fccd08..0deec8ed6 100644 --- a/source/core/platform.cpp +++ b/source/core/platform.cpp @@ -52,7 +52,7 @@ SLANG_COMPILE_TIME_ASSERT(E_OUTOFMEMORY == SLANG_E_OUT_OF_MEMORY); { builderOut << " "; // Convert to string - builderOut.Append(String::FromWString(buffer)); + builderOut.Append(String::fromWString(buffer)); LocalFree(buffer); return SLANG_OK; } diff --git a/source/core/slang-byte-encode-util.cpp b/source/core/slang-byte-encode-util.cpp index 6eabdc16f..47ab824a4 100644 --- a/source/core/slang-byte-encode-util.cpp +++ b/source/core/slang-byte-encode-util.cpp @@ -100,7 +100,7 @@ namespace Slang { /* static */void ByteEncodeUtil::encodeLiteUInt32(const uint32_t* in, size_t num, List<uint8_t>& encodeArrayOut) { // Make sure there is at least enough space for all bytes - encodeArrayOut.SetSize(num); + encodeArrayOut.setCount(num); uint8_t* encodeOut = encodeArrayOut.begin(); uint8_t* encodeOutEnd = encodeArrayOut.end(); @@ -112,13 +112,13 @@ namespace Slang { { const size_t offset = size_t(encodeOut - encodeArrayOut.begin()); - const UInt oldCapacity = encodeArrayOut.Capacity(); + const UInt oldCapacity = encodeArrayOut.getCapacity(); // Make some more space - encodeArrayOut.Reserve(oldCapacity + (oldCapacity >> 1) + kMaxLiteEncodeUInt32); + encodeArrayOut.reserve(oldCapacity + (oldCapacity >> 1) + kMaxLiteEncodeUInt32); // Make the size the capacity - const UInt capacity = encodeArrayOut.Capacity(); - encodeArrayOut.SetSize(capacity); + const UInt capacity = encodeArrayOut.getCapacity(); + encodeArrayOut.setCount(capacity); encodeOut = encodeArrayOut.begin() + offset; encodeOutEnd = encodeArrayOut.end(); @@ -152,8 +152,8 @@ namespace Slang { } } - encodeArrayOut.SetSize(UInt(encodeOut - encodeArrayOut.begin())); - encodeArrayOut.Compress(); + encodeArrayOut.setCount(UInt(encodeOut - encodeArrayOut.begin())); + encodeArrayOut.compress(); } /* static */int ByteEncodeUtil::encodeLiteUInt32(uint32_t in, uint8_t out[kMaxLiteEncodeUInt32]) diff --git a/source/core/slang-free-list.h b/source/core/slang-free-list.h index dfa924797..62c2b9d93 100644 --- a/source/core/slang-free-list.h +++ b/source/core/slang-free-list.h @@ -1,9 +1,9 @@ -#ifndef SLANG_FREE_LIST_H +#ifndef SLANG_FREE_LIST_H #define SLANG_FREE_LIST_H #include "../../slang.h" -#include <assert.h> +#include "common.h" #include <stdlib.h> #include <string.h> @@ -141,4 +141,4 @@ SLANG_FORCE_INLINE void FreeList::deallocate(void* data) } // namespace Slang -#endif // SLANG_FREE_LIST_H
\ No newline at end of file +#endif // SLANG_FREE_LIST_H diff --git a/source/core/slang-io.cpp b/source/core/slang-io.cpp index 332718cea..82a2e5a35 100644 --- a/source/core/slang-io.cpp +++ b/source/core/slang-io.cpp @@ -35,28 +35,28 @@ namespace Slang { #ifdef _WIN32 struct _stat32 statVar; - return ::_wstat32(((String)fileName).ToWString(), &statVar) != -1; + return ::_wstat32(((String)fileName).toWString(), &statVar) != -1; #else struct stat statVar; - return ::stat(fileName.Buffer(), &statVar) == 0; + return ::stat(fileName.getBuffer(), &statVar) == 0; #endif } String Path::truncateExt(const String& path) { - UInt dotPos = path.LastIndexOf('.'); + UInt dotPos = path.lastIndexOf('.'); if (dotPos != -1) - return path.SubString(0, dotPos); + return path.subString(0, dotPos); else return path; } String Path::replaceExt(const String& path, const char* newExt) { - StringBuilder sb(path.Length()+10); - UInt dotPos = path.LastIndexOf('.'); + StringBuilder sb(path.getLength()+10); + UInt dotPos = path.lastIndexOf('.'); if (dotPos == -1) - dotPos = path.Length(); - sb.Append(path.Buffer(), dotPos); + dotPos = path.getLength(); + sb.Append(path.getBuffer(), dotPos); sb.Append('.'); sb.Append(newExt); return sb.ProduceString(); @@ -64,8 +64,8 @@ namespace Slang static UInt findLastSeparator(String const& path) { - UInt slashPos = path.LastIndexOf('/'); - UInt backslashPos = path.LastIndexOf('\\'); + UInt slashPos = path.lastIndexOf('/'); + UInt backslashPos = path.lastIndexOf('\\'); if (slashPos == -1) return backslashPos; if (backslashPos == -1) return slashPos; @@ -83,7 +83,7 @@ namespace Slang if (pos != -1) { pos = pos + 1; - return path.SubString(pos, path.Length() - pos); + return path.subString(pos, path.getLength() - pos); } else { @@ -93,16 +93,16 @@ namespace Slang String Path::getFileNameWithoutExt(const String& path) { String fileName = getFileName(path); - UInt dotPos = fileName.LastIndexOf('.'); + UInt dotPos = fileName.lastIndexOf('.'); if (dotPos == -1) return fileName; - return fileName.SubString(0, dotPos); + return fileName.subString(0, dotPos); } String Path::getFileExt(const String& path) { - UInt dotPos = path.LastIndexOf('.'); + UInt dotPos = path.lastIndexOf('.'); if (dotPos != -1) - return path.SubString(dotPos+1, path.Length()-dotPos-1); + return path.subString(dotPos+1, path.getLength()-dotPos-1); else return ""; } @@ -110,28 +110,28 @@ namespace Slang { UInt pos = findLastSeparator(path); if (pos != -1) - return path.SubString(0, pos); + return path.subString(0, pos); else return ""; } String Path::combine(const String& path1, const String& path2) { - if (path1.Length() == 0) return path2; - StringBuilder sb(path1.Length()+path2.Length()+2); + if (path1.getLength() == 0) return path2; + StringBuilder sb(path1.getLength()+path2.getLength()+2); sb.Append(path1); - if (!path1.EndsWith('\\') && !path1.EndsWith('/')) + if (!path1.endsWith('\\') && !path1.endsWith('/')) sb.Append(kPathDelimiter); sb.Append(path2); return sb.ProduceString(); } String Path::combine(const String& path1, const String& path2, const String& path3) { - StringBuilder sb(path1.Length()+path2.Length()+path3.Length()+3); + StringBuilder sb(path1.getLength()+path2.getLength()+path3.getLength()+3); sb.Append(path1); - if (!path1.EndsWith('\\') && !path1.EndsWith('/')) + if (!path1.endsWith('\\') && !path1.endsWith('/')) sb.Append(kPathDelimiter); sb.Append(path2); - if (!path2.EndsWith('\\') && !path2.EndsWith('/')) + if (!path2.endsWith('\\') && !path2.endsWith('/')) sb.Append(kPathDelimiter); sb.Append(path3); return sb.ProduceString(); @@ -191,7 +191,7 @@ namespace Slang /* static */void Path::split(const UnownedStringSlice& path, List<UnownedStringSlice>& splitOut) { - splitOut.Clear(); + splitOut.clear(); const char* start = path.begin(); const char* end = path.end(); @@ -202,21 +202,21 @@ namespace Slang // Find the split while (cur < end && !isDelimiter(*cur)) cur++; - splitOut.Add(UnownedStringSlice(start, cur)); + splitOut.add(UnownedStringSlice(start, cur)); // Next start = cur + 1; } // Okay if the end is empty. And we aren't with a spec like // or c:/ , then drop the final slash - if (splitOut.Count() > 1 && splitOut.Last().size() == 0) + if (splitOut.getCount() > 1 && splitOut.getLast().size() == 0) { - if (splitOut.Count() == 2 && isDriveSpecification(splitOut[0])) + if (splitOut.getCount() == 2 && isDriveSpecification(splitOut[0])) { return; } // Remove the last - splitOut.RemoveLast(); + splitOut.removeLast(); } } @@ -241,13 +241,13 @@ namespace Slang split(path, splitPath); // Strictly speaking we could do something about case on platforms like window, but here we won't worry about that - for (int i = 0; i < int(splitPath.Count()); i++) + for (Index i = 0; i < splitPath.getCount(); i++) { const UnownedStringSlice& cur = splitPath[i]; - if (cur == "." && splitPath.Count() > 1) + if (cur == "." && splitPath.getCount() > 1) { // Just remove it - splitPath.RemoveAt(i); + splitPath.removeAt(i); i--; } else if (cur == ".." && i > 0) @@ -259,20 +259,20 @@ namespace Slang // Can't do it continue; } - splitPath.RemoveRange(i - 1, 2); + splitPath.removeRange(i - 1, 2); i -= 2; } } // If its empty it must be . - if (splitPath.Count() == 0) + if (splitPath.getCount() == 0) { - splitPath.Add(UnownedStringSlice::fromLiteral(".")); + splitPath.add(UnownedStringSlice::fromLiteral(".")); } // Reconstruct the string StringBuilder builder; - for (int i = 0; i < int(splitPath.Count()); i++) + for (Index i = 0; i < splitPath.getCount(); i++) { if (i > 0) { @@ -287,9 +287,9 @@ namespace Slang bool Path::createDirectory(const String& path) { #if defined(_WIN32) - return _wmkdir(path.ToWString()) == 0; + return _wmkdir(path.toWString()) == 0; #else - return mkdir(path.Buffer(), 0777) == 0; + return mkdir(path.getBuffer(), 0777) == 0; #endif } @@ -298,7 +298,7 @@ namespace Slang #ifdef _WIN32 // https://msdn.microsoft.com/en-us/library/14h5k7ff.aspx struct _stat32 statVar; - if (::_wstat32(String(path).ToWString(), &statVar) == 0) + if (::_wstat32(String(path).toWString(), &statVar) == 0) { if (statVar.st_mode & _S_IFDIR) { @@ -316,7 +316,7 @@ namespace Slang return SLANG_E_NOT_FOUND; #else struct stat statVar; - if (::stat(path.Buffer(), &statVar) == 0) + if (::stat(path.getBuffer(), &statVar) == 0) { if (S_ISDIR(statVar.st_mode)) { @@ -340,13 +340,13 @@ namespace Slang { #if defined(_WIN32) // https://msdn.microsoft.com/en-us/library/506720ff.aspx - wchar_t* absPath = ::_wfullpath(nullptr, path.ToWString(), 0); + wchar_t* absPath = ::_wfullpath(nullptr, path.toWString(), 0); if (!absPath) { return SLANG_FAIL; } - canonicalPathOut = String::FromWString(absPath); + canonicalPathOut = String::fromWString(absPath); ::free(absPath); return SLANG_OK; #else @@ -432,15 +432,15 @@ namespace Slang return SLANG_OK; # else String text = Slang::File::readAllText("/proc/self/maps"); - UInt startIndex = text.IndexOf('/'); - if (startIndex == UInt(-1)) + Index startIndex = text.indexOf('/'); + if (startIndex == Index(-1)) { return SLANG_FAIL; } - UInt endIndex = text.IndexOf("\n", startIndex); - endIndex = (endIndex == UInt(-1)) ? text.Length() : endIndex; + Index endIndex = text.indexOf("\n", startIndex); + endIndex = (endIndex == Index(-1)) ? text.getLength() : endIndex; - auto path = text.SubString(startIndex, endIndex - startIndex); + auto path = text.subString(startIndex, endIndex - startIndex); if (path.getLength() < bufferSize) { @@ -476,17 +476,17 @@ namespace Slang { List<char> buffer; // Guess an initial buffer size - buffer.SetSize(1024); + buffer.setCount(1024); while (true) { - const size_t size = buffer.Count(); + const size_t size = size_t(buffer.getCount()); size_t bufferSize = size; - SlangResult res = _calcExectuablePath(buffer.Buffer(), &bufferSize); + SlangResult res = _calcExectuablePath(buffer.getBuffer(), &bufferSize); if (SLANG_SUCCEEDED(res)) { - return String(buffer.Buffer()); + return String(buffer.getBuffer()); } if (res != SLANG_E_BUFFER_TOO_SMALL) @@ -497,7 +497,7 @@ namespace Slang // If bufferSize changed it should be the exact fit size, else we just make the buffer bigger by a guess (50% bigger) bufferSize = (bufferSize > size) ? bufferSize : (bufferSize + bufferSize / 2); - buffer.SetSize(bufferSize); + buffer.setCount(Index(bufferSize)); } } @@ -522,7 +522,7 @@ namespace Slang unsigned char ch; int read = (int)fs->Read(&ch, 1); if (read) - buffer.Add(ch); + buffer.add(ch); else break; } diff --git a/source/core/slang-memory-arena.h b/source/core/slang-memory-arena.h index 52400f9ed..b9066e198 100644 --- a/source/core/slang-memory-arena.h +++ b/source/core/slang-memory-arena.h @@ -3,8 +3,6 @@ #include "../../slang.h" -#include <assert.h> - #include <stdlib.h> #include <string.h> diff --git a/source/core/slang-object-scope-manager.cpp b/source/core/slang-object-scope-manager.cpp index 313bd4cd5..2e7b7dfe3 100644 --- a/source/core/slang-object-scope-manager.cpp +++ b/source/core/slang-object-scope-manager.cpp @@ -5,8 +5,8 @@ namespace Slang { void ObjectScopeManager::_releaseAll() { RefObject*const* objs = m_objs.begin(); - const int numObjs = int(m_objs.Count()); - for (int i = 0; i < numObjs; ++i) + const Index numObjs = m_objs.getCount(); + for (Index i = 0; i < numObjs; ++i) { objs[i]->decreaseReference(); } diff --git a/source/core/slang-object-scope-manager.h b/source/core/slang-object-scope-manager.h index 14008a490..660a7cace 100644 --- a/source/core/slang-object-scope-manager.h +++ b/source/core/slang-object-scope-manager.h @@ -1,4 +1,4 @@ -#ifndef SLANG_OBJECT_SCOPE_MANAGER_H +#ifndef SLANG_OBJECT_SCOPE_MANAGER_H #define SLANG_OBJECT_SCOPE_MANAGER_H #include "smart-pointer.h" @@ -48,7 +48,7 @@ RefObject* ObjectScopeManager::addMaybeNull(RefObject* obj) if (obj) { obj->addReference(); - m_objs.Add(obj); + m_objs.add(obj); } return obj; } @@ -58,10 +58,10 @@ RefObject* ObjectScopeManager::add(RefObject* obj) { SLANG_ASSERT(obj); obj->addReference(); - m_objs.Add(obj); + m_objs.add(obj); return obj; } } // namespace Slang -#endif // SLANG_OBJECT_SCOPE_MANAGER_H
\ No newline at end of file +#endif // SLANG_OBJECT_SCOPE_MANAGER_H diff --git a/source/core/slang-random-generator.h b/source/core/slang-random-generator.h index 7b3e42288..cc25aadf3 100644 --- a/source/core/slang-random-generator.h +++ b/source/core/slang-random-generator.h @@ -3,8 +3,6 @@ #include "../../slang.h" -#include <assert.h> - #include <stdlib.h> #include <string.h> @@ -94,4 +92,4 @@ typedef Mt19937RandomGenerator DefaultRandomGenerator; } // namespace Slang -#endif // SLANG_RANDOM_GENERATOR_H
\ No newline at end of file +#endif // SLANG_RANDOM_GENERATOR_H diff --git a/source/core/slang-render-api-util.cpp b/source/core/slang-render-api-util.cpp index 80f2225d9..05def0fe3 100644 --- a/source/core/slang-render-api-util.cpp +++ b/source/core/slang-render-api-util.cpp @@ -62,7 +62,7 @@ UnownedStringSlice RenderApiUtil::getApiName(RenderApiType type) if (names.indexOf(',') >= 0) { StringUtil::split(names, ',', namesList); - if (namesList.IndexOf(name) != UInt(-1)) + if (namesList.indexOf(name) != Index(-1)) { return apiInfo.type; } diff --git a/source/core/slang-string-slice-pool.cpp b/source/core/slang-string-slice-pool.cpp index 797da5a0f..e3d9d8809 100644 --- a/source/core/slang-string-slice-pool.cpp +++ b/source/core/slang-string-slice-pool.cpp @@ -16,7 +16,7 @@ StringSlicePool::StringSlicePool() : void StringSlicePool::clear() { - m_slices.SetSize(2); + m_slices.setCount(2); m_slices[0] = UnownedStringSlice((const char*)nullptr, (const char*)nullptr); m_slices[1] = UnownedStringSlice::fromLiteral(""); @@ -38,9 +38,9 @@ StringSlicePool::Handle StringSlicePool::add(const Slice& slice) // Create a scoped copy UnownedStringSlice scopePath(m_arena.allocateString(slice.begin(), slice.size()), slice.size()); - const int index = int(m_slices.Count()); + const auto index = m_slices.getCount(); - m_slices.Add(scopePath); + m_slices.add(scopePath); m_map.Add(scopePath, Handle(index)); return Handle(index); } diff --git a/source/core/slang-string-slice-pool.h b/source/core/slang-string-slice-pool.h index 08cd819ab..cf8f63c81 100644 --- a/source/core/slang-string-slice-pool.h +++ b/source/core/slang-string-slice-pool.h @@ -46,7 +46,7 @@ public: const List<UnownedStringSlice>& getSlices() const { return m_slices; } /// Get the number of slices - int getNumSlices() const { return int(m_slices.Count()); } + int getNumSlices() const { return int(m_slices.getCount()); } /// Convert a handle to and index. (A handle is just an index!) static int asIndex(Handle handle) { return int(handle); } diff --git a/source/core/slang-string-util.cpp b/source/core/slang-string-util.cpp index b7c6780e1..11d6846f0 100644 --- a/source/core/slang-string-util.cpp +++ b/source/core/slang-string-util.cpp @@ -17,7 +17,7 @@ static const Guid IID_ISlangBlob = SLANG_UUID_ISlangBlob; /* static */void StringUtil::split(const UnownedStringSlice& in, char splitChar, List<UnownedStringSlice>& slicesOut) { - slicesOut.Clear(); + slicesOut.clear(); const char* start = in.begin(); const char* end = in.end(); @@ -32,7 +32,7 @@ static const Guid IID_ISlangBlob = SLANG_UUID_ISlangBlob; } // Add to output - slicesOut.Add(UnownedStringSlice(start, cur)); + slicesOut.add(UnownedStringSlice(start, cur)); // Skip the split character, if at end we are okay anyway start = cur + 1; @@ -178,13 +178,13 @@ ComPtr<ISlangBlob> StringUtil::createStringBlob(const String& string) return slice; } - const UInt numChars = slice.size(); + const Index numChars = slice.size(); const char* srcChars = slice.begin(); StringBuilder builder; char* dstChars = builder.prepareForAppend(numChars); - for (UInt i = 0; i < numChars; ++i) + for (Index i = 0; i < numChars; ++i) { char c = srcChars[i]; dstChars[i] = (c == fromChar) ? toChar : c; @@ -196,7 +196,7 @@ ComPtr<ISlangBlob> StringUtil::createStringBlob(const String& string) /* static */String StringUtil::calcCharReplaced(const String& string, char fromChar, char toChar) { - return (fromChar == toChar || string.IndexOf(fromChar) == UInt(-1)) ? string : calcCharReplaced(string.getUnownedSlice(), fromChar, toChar); + return (fromChar == toChar || string.indexOf(fromChar) == Index(-1)) ? string : calcCharReplaced(string.getUnownedSlice(), fromChar, toChar); } diff --git a/source/core/slang-string-util.h b/source/core/slang-string-util.h index 3288899fc..40fda31c4 100644 --- a/source/core/slang-string-util.h +++ b/source/core/slang-string-util.h @@ -20,8 +20,8 @@ public: SLANG_REF_OBJECT_IUNKNOWN_ALL // ISlangBlob - SLANG_NO_THROW void const* SLANG_MCALL getBufferPointer() SLANG_OVERRIDE { return m_string.Buffer(); } - SLANG_NO_THROW size_t SLANG_MCALL getBufferSize() SLANG_OVERRIDE { return m_string.Length(); } + SLANG_NO_THROW void const* SLANG_MCALL getBufferPointer() SLANG_OVERRIDE { return m_string.getBuffer(); } + SLANG_NO_THROW size_t SLANG_MCALL getBufferSize() SLANG_OVERRIDE { return m_string.getLength(); } /// Get the contained string SLANG_FORCE_INLINE const String& getString() const { return m_string; } diff --git a/source/core/slang-string.cpp b/source/core/slang-string.cpp index 28acde6ac..9a908c93e 100644 --- a/source/core/slang-string.cpp +++ b/source/core/slang-string.cpp @@ -14,20 +14,20 @@ namespace Slang // OSString OSString::OSString() - : beginData(0) - , endData(0) + : m_begin(0) + , m_end(0) {} OSString::OSString(wchar_t* begin, wchar_t* end) - : beginData(begin) - , endData(end) + : m_begin(begin) + , m_end(end) {} OSString::~OSString() { - if (beginData) + if (m_begin) { - delete[] beginData; + delete[] m_begin; } } @@ -35,12 +35,12 @@ namespace Slang wchar_t const* OSString::begin() const { - return beginData ? beginData : kEmptyOSString; + return m_begin ? m_begin : kEmptyOSString; } wchar_t const* OSString::end() const { - return endData ? endData : kEmptyOSString; + return m_end ? m_end : kEmptyOSString; } // UnownedStringSlice @@ -89,13 +89,13 @@ namespace Slang {} StringSlice::StringSlice(String const& str) - : representation(str.buffer) + : representation(str.m_buffer) , beginIndex(0) - , endIndex(str.Length()) + , endIndex(str.getLength()) {} StringSlice::StringSlice(String const& str, UInt beginIndex, UInt endIndex) - : representation(str.buffer) + : representation(str.m_buffer) , beginIndex(beginIndex) , endIndex(endIndex) {} @@ -128,25 +128,25 @@ namespace Slang int StringToInt(const String & str, int radix) { - if (str.StartsWith("0x")) - return (int)strtoll(str.Buffer(), NULL, 16); + if (str.startsWith("0x")) + return (int)strtoll(str.getBuffer(), NULL, 16); else - return (int)strtoll(str.Buffer(), NULL, radix); + return (int)strtoll(str.getBuffer(), NULL, radix); } unsigned int StringToUInt(const String & str, int radix) { - if (str.StartsWith("0x")) - return (unsigned int)strtoull(str.Buffer(), NULL, 16); + if (str.startsWith("0x")) + return (unsigned int)strtoull(str.getBuffer(), NULL, 16); else - return (unsigned int)strtoull(str.Buffer(), NULL, radix); + return (unsigned int)strtoull(str.getBuffer(), NULL, radix); } double StringToDouble(const String & str) { - return (double)strtod(str.Buffer(), NULL); + return (double)strtod(str.getBuffer(), NULL); } float StringToFloat(const String & str) { - return strtof(str.Buffer(), NULL); + return strtof(str.getBuffer(), NULL); } #if 0 @@ -165,7 +165,7 @@ namespace Slang } #endif - String String::FromWString(const wchar_t * wstr) + String String::fromWString(const wchar_t * wstr) { #ifdef _WIN32 return Slang::Encoding::UTF16->ToString((const char*)wstr, (int)(wcslen(wstr) * sizeof(wchar_t))); @@ -174,7 +174,7 @@ namespace Slang #endif } - String String::FromWString(const wchar_t * wstr, const wchar_t * wend) + String String::fromWString(const wchar_t * wstr, const wchar_t * wend) { #ifdef _WIN32 return Slang::Encoding::UTF16->ToString((const char*)wstr, (int)((wend - wstr) * sizeof(wchar_t))); @@ -183,7 +183,7 @@ namespace Slang #endif } - String String::FromWChar(const wchar_t ch) + String String::fromWChar(const wchar_t ch) { #ifdef _WIN32 return Slang::Encoding::UTF16->ToString((const char*)&ch, (int)(sizeof(wchar_t))); @@ -192,7 +192,7 @@ namespace Slang #endif } - String String::FromUnicodePoint(unsigned int codePoint) + String String::fromUnicodePoint(unsigned int codePoint) { char buf[6]; int len = Slang::EncodeUnicodePointToUTF8(buf, (int)codePoint); @@ -200,9 +200,9 @@ namespace Slang return String(buf); } - OSString String::ToWString(UInt* outLength) const + OSString String::toWString(Index* outLength) const { - if (!buffer) + if (!m_buffer) { return OSString(); } @@ -223,17 +223,17 @@ namespace Slang break; } - auto length = buf.Count() / sizeof(wchar_t); + auto length = Index(buf.getCount() / sizeof(wchar_t)); if (outLength) *outLength = length; for(int ii = 0; ii < sizeof(wchar_t); ++ii) - buf.Add(0); + buf.add(0); - wchar_t* beginData = (wchar_t*)buf.Buffer(); + wchar_t* beginData = (wchar_t*)buf.getBuffer(); wchar_t* endData = beginData + length; - buf.ReleaseBuffer(); + buf.detachBuffer(); return OSString(beginData, endData); } @@ -241,55 +241,55 @@ namespace Slang // - void String::ensureUniqueStorageWithCapacity(UInt requiredCapacity) + void String::ensureUniqueStorageWithCapacity(Index requiredCapacity) { - if (buffer && buffer->isUniquelyReferenced() && buffer->capacity >= requiredCapacity) + if (m_buffer && m_buffer->isUniquelyReferenced() && m_buffer->capacity >= requiredCapacity) return; - UInt newCapacity = buffer ? 2*buffer->capacity : 16; + Index newCapacity = m_buffer ? 2 * m_buffer->capacity : 16; if (newCapacity < requiredCapacity) { newCapacity = requiredCapacity; } - UInt length = getLength(); + Index length = getLength(); StringRepresentation* newRepresentation = StringRepresentation::createWithCapacityAndLength(newCapacity, length); - if (buffer) + if (m_buffer) { - memcpy(newRepresentation->getData(), buffer->getData(), length + 1); + memcpy(newRepresentation->getData(), m_buffer->getData(), length + 1); } - buffer = newRepresentation; + m_buffer = newRepresentation; } - char* String::prepareForAppend(UInt count) + char* String::prepareForAppend(Index count) { auto oldLength = getLength(); auto newLength = oldLength + count; ensureUniqueStorageWithCapacity(newLength); return getData() + oldLength; } - void String::appendInPlace(const char* chars, UInt count) + void String::appendInPlace(const char* chars, Index count) { SLANG_UNUSED(chars); if (count > 0) { - SLANG_ASSERT(buffer && buffer->isUniquelyReferenced()); + SLANG_ASSERT(m_buffer && m_buffer->isUniquelyReferenced()); auto oldLength = getLength(); auto newLength = oldLength + count; - char* dst = buffer->getData(); + char* dst = m_buffer->getData(); // Make sure the input buffer is the same one returned from prepareForAppend SLANG_ASSERT(chars == dst + oldLength); // It has to fit within the capacity - SLANG_ASSERT(newLength <= buffer->capacity); + SLANG_ASSERT(newLength <= m_buffer->capacity); // We just need to modify the length - buffer->length = newLength; + m_buffer->length = newLength; // And mark with a terminating 0 dst[newLength] = 0; @@ -307,7 +307,7 @@ namespace Slang memcpy(getData() + oldLength, textBegin, textLength); getData()[newLength] = 0; - buffer->length = newLength; + m_buffer->length = newLength; } void String::append(char const* str) @@ -325,9 +325,9 @@ namespace Slang void String::append(String const& str) { - if (!buffer) + if (!m_buffer) { - buffer = str.buffer; + m_buffer = str.m_buffer; return; } @@ -350,7 +350,7 @@ namespace Slang char* data = prepareForAppend(kCount); auto count = IntToAscii(data, value, radix); ReverseInternalAscii(data, count); - buffer->length += count; + m_buffer->length += count; } void String::append(uint32_t value, int radix) @@ -359,7 +359,7 @@ namespace Slang char* data = prepareForAppend(kCount); auto count = IntToAscii(data, value, radix); ReverseInternalAscii(data, count); - buffer->length += count; + m_buffer->length += count; } void String::append(int64_t value, int radix) @@ -368,7 +368,7 @@ namespace Slang char* data = prepareForAppend(kCount); auto count = IntToAscii(data, value, radix); ReverseInternalAscii(data, count); - buffer->length += count; + m_buffer->length += count; } void String::append(uint64_t value, int radix) @@ -377,7 +377,7 @@ namespace Slang char* data = prepareForAppend(kCount); auto count = IntToAscii(data, value, radix); ReverseInternalAscii(data, count); - buffer->length += count; + m_buffer->length += count; } void String::append(float val, const char * format) @@ -385,7 +385,7 @@ namespace Slang enum { kCount = 128 }; char* data = prepareForAppend(kCount); sprintf_s(data, kCount, format, val); - buffer->length += strnlen_s(data, kCount); + m_buffer->length += strnlen_s(data, kCount); } void String::append(double val, const char * format) @@ -393,6 +393,6 @@ namespace Slang enum { kCount = 128 }; char* data = prepareForAppend(kCount); sprintf_s(data, kCount, format, val); - buffer->length += strnlen_s(data, kCount); + m_buffer->length += strnlen_s(data, kCount); } } diff --git a/source/core/slang-string.h b/source/core/slang-string.h index 4c87ce81e..82eda74ac 100644 --- a/source/core/slang-string.h +++ b/source/core/slang-string.h @@ -66,44 +66,44 @@ namespace Slang { public: UnownedStringSlice() - : beginData(nullptr) - , endData(nullptr) + : m_begin(nullptr) + , m_end(nullptr) {} explicit UnownedStringSlice(char const* a) : - beginData(a), - endData(a + strlen(a)) + m_begin(a), + m_end(a + strlen(a)) {} UnownedStringSlice(char const* b, char const* e) - : beginData(b) - , endData(e) + : m_begin(b) + , m_end(e) {} UnownedStringSlice(char const* b, size_t len) - : beginData(b) - , endData(b + len) + : m_begin(b) + , m_end(b + len) {} char const* begin() const { - return beginData; + return m_begin; } char const* end() const { - return endData; + return m_end; } - UInt size() const + Index size() const { - return endData - beginData; + return Index(m_end - m_begin); } int indexOf(char c) const { - const int size = int(endData - beginData); + const int size = int(m_end - m_begin); for (int i = 0; i < size; ++i) { - if (beginData[i] == c) + if (m_begin[i] == c) { return i; } @@ -111,10 +111,10 @@ namespace Slang return -1; } - const char& operator[](UInt i) const + const char& operator[](Index i) const { - assert(i < UInt(endData - beginData)); - return beginData[i]; + assert(i >= 0 && i < Index(m_end - m_begin)); + return m_begin[i]; } bool operator==(UnownedStringSlice const& other) const @@ -125,7 +125,7 @@ namespace Slang bool operator==(char const* str) const { - return (*this) == UnownedStringSlice(str, str + strlen(str)); + return (*this) == UnownedStringSlice(str, str + ::strlen(str)); } bool operator!=(UnownedStringSlice const& other) const @@ -141,15 +141,15 @@ namespace Slang int GetHashCode() const { - return Slang::GetHashCode(beginData, size_t(endData - beginData)); + return Slang::GetHashCode(m_begin, size_t(m_end - m_begin)); } template <size_t SIZE> SLANG_FORCE_INLINE static UnownedStringSlice fromLiteral(const char (&in)[SIZE]) { return UnownedStringSlice(in, SIZE - 1); } private: - char const* beginData; - char const* endData; + char const* m_begin; + char const* m_end; }; // A `StringRepresentation` provides the backing storage for @@ -157,10 +157,10 @@ namespace Slang class StringRepresentation : public RefObject { public: - UInt length; - UInt capacity; + Index length; + Index capacity; - SLANG_FORCE_INLINE UInt getLength() const + SLANG_FORCE_INLINE Index getLength() const { return length; } @@ -189,7 +189,7 @@ namespace Slang return (a == b) || asSlice(a) == asSlice(b); } - static StringRepresentation* createWithCapacityAndLength(UInt capacity, UInt length) + static StringRepresentation* createWithCapacityAndLength(Index capacity, Index length) { SLANG_ASSERT(capacity >= length); void* allocation = operator new(sizeof(StringRepresentation) + capacity + 1); @@ -200,17 +200,17 @@ namespace Slang return obj; } - static StringRepresentation* createWithCapacity(UInt capacity) + static StringRepresentation* createWithCapacity(Index capacity) { return createWithCapacityAndLength(capacity, 0); } - static StringRepresentation* createWithLength(UInt length) + static StringRepresentation* createWithLength(Index length) { return createWithCapacityAndLength(length, length); } - StringRepresentation* cloneWithCapacity(UInt newCapacity) + StringRepresentation* cloneWithCapacity(Index newCapacity) { StringRepresentation* newObj = createWithCapacityAndLength(newCapacity, length); memcpy(getData(), newObj->getData(), length + 1); @@ -222,11 +222,11 @@ namespace Slang return cloneWithCapacity(length); } - StringRepresentation* ensureCapacity(UInt required) + StringRepresentation* ensureCapacity(Index required) { if (capacity >= required) return this; - UInt newCapacity = capacity; + Index newCapacity = capacity; if (!newCapacity) newCapacity = 16; // TODO: figure out good value for minimum capacity while (newCapacity < required) @@ -305,8 +305,8 @@ namespace Slang wchar_t const* end() const; private: - wchar_t* beginData; - wchar_t* endData; + wchar_t* m_begin; + wchar_t* m_end; }; /*! @@ -322,38 +322,34 @@ namespace Slang char* getData() const { - return buffer ? buffer->getData() : (char*)""; + return m_buffer ? m_buffer->getData() : (char*)""; } - UInt getLength() const - { - return buffer ? buffer->getLength() : 0; - } - - void ensureUniqueStorageWithCapacity(UInt capacity); - RefPtr<StringRepresentation> buffer; + void ensureUniqueStorageWithCapacity(Index capacity); + + RefPtr<StringRepresentation> m_buffer; public: explicit String(StringRepresentation* buffer) - : buffer(buffer) + : m_buffer(buffer) {} - static String FromWString(const wchar_t * wstr); - static String FromWString(const wchar_t * wstr, const wchar_t * wend); - static String FromWChar(const wchar_t ch); - static String FromUnicodePoint(unsigned int codePoint); + static String fromWString(const wchar_t * wstr); + static String fromWString(const wchar_t * wstr, const wchar_t * wend); + static String fromWChar(const wchar_t ch); + static String fromUnicodePoint(unsigned int codePoint); String() { } /// Returns a buffer which can hold at least count chars - char* prepareForAppend(UInt count); + char* prepareForAppend(Index count); /// Append data written to buffer output via 'prepareForAppend' directly written 'inplace' - void appendInPlace(const char* chars, UInt count); + void appendInPlace(const char* chars, Index count); - SLANG_FORCE_INLINE StringRepresentation* getStringRepresentation() const { return buffer; } + SLANG_FORCE_INLINE StringRepresentation* getStringRepresentation() const { return m_buffer; } const char * begin() const { @@ -439,14 +435,14 @@ namespace Slang } String(String const& str) { - buffer = str.buffer; + m_buffer = str.m_buffer; #if 0 this->operator=(str); #endif } String(String&& other) { - buffer = _Move(other.buffer); + m_buffer = _Move(other.m_buffer); } String(StringSlice const& slice) @@ -461,74 +457,79 @@ namespace Slang ~String() { - buffer = 0; + m_buffer = 0; } String & operator=(const String & str) { - buffer = str.buffer; + m_buffer = str.m_buffer; return *this; } String & operator=(String&& other) { - buffer = _Move(other.buffer); + m_buffer = _Move(other.m_buffer); return *this; } - char operator[](UInt id) const + char operator[](Index id) const { -#if _DEBUG - if (id < 0 || id >= getLength()) - throw "Operator[]: index out of range."; -#endif + SLANG_ASSERT(id >= 0 && id < getLength()); return begin()[id]; } + Index getLength() const + { + return m_buffer ? m_buffer->getLength() : 0; + } + friend String operator+(const char*op1, const String & op2); friend String operator+(const String & op1, const char * op2); friend String operator+(const String & op1, const String & op2); - StringSlice TrimStart() const + StringSlice trimStart() const { - if (!buffer) + if (!m_buffer) return StringSlice(); - UInt startIndex = 0; + Index startIndex = 0; + const char*const data = getData(); while (startIndex < getLength() && - (getData()[startIndex] == ' ' || getData()[startIndex] == '\t' || getData()[startIndex] == '\r' || getData()[startIndex] == '\n')) + (data[startIndex] == ' ' || data[startIndex] == '\t' || data[startIndex] == '\r' || data[startIndex] == '\n')) startIndex++; - return StringSlice(buffer, startIndex, getLength()); + return StringSlice(m_buffer, startIndex, getLength()); } - StringSlice TrimEnd() const + StringSlice trimEnd() const { - if (!buffer) + if (!m_buffer) return StringSlice(); - UInt endIndex = getLength(); + Index endIndex = getLength(); + const char*const data = getData(); while (endIndex > 0 && - (getData()[endIndex-1] == ' ' || getData()[endIndex-1] == '\t' || getData()[endIndex-1] == '\r' || getData()[endIndex-1] == '\n')) + (data[endIndex-1] == ' ' || data[endIndex-1] == '\t' || data[endIndex-1] == '\r' || data[endIndex-1] == '\n')) endIndex--; - return StringSlice(buffer, 0, endIndex); + return StringSlice(m_buffer, 0, endIndex); } - StringSlice Trim() const + StringSlice trim() const { - if (!buffer) + if (!m_buffer) return StringSlice(); - UInt startIndex = 0; + Index startIndex = 0; + const char*const data = getData(); while (startIndex < getLength() && - (getData()[startIndex] == ' ' || getData()[startIndex] == '\t')) + (data[startIndex] == ' ' || data[startIndex] == '\t')) startIndex++; - UInt endIndex = getLength(); + Index endIndex = getLength(); while (endIndex > startIndex && - (getData()[endIndex-1] == ' ' || getData()[endIndex-1] == '\t')) + (data[endIndex-1] == ' ' || data[endIndex-1] == '\t')) endIndex--; - return StringSlice(buffer, startIndex, endIndex); + return StringSlice(m_buffer, startIndex, endIndex); } - StringSlice SubString(UInt id, UInt len) const + StringSlice subString(Index id, Index len) const { if (len == 0) return StringSlice(); @@ -541,17 +542,17 @@ namespace Slang if (len < 0) throw "SubString: length less than zero."; #endif - return StringSlice(buffer, id, id + len); + return StringSlice(m_buffer, id, id + len); } - char const* Buffer() const + char const* getBuffer() const { return getData(); } - OSString ToWString(UInt* len = 0) const; + OSString toWString(Index* len = 0) const; - bool Equals(const String & str, bool caseSensitive = true) + bool equals(const String & str, bool caseSensitive = true) { if (caseSensitive) return (strcmp(begin(), str.begin()) == 0); @@ -598,7 +599,7 @@ namespace Slang return (strcmp(begin(), str.begin()) <= 0); } - String ToUpper() const + String toUpper() const { String result; for (auto c : *this) @@ -609,7 +610,7 @@ namespace Slang return result; } - String ToLower() const + String toLower() const { String result; for (auto c : *this) @@ -620,108 +621,114 @@ namespace Slang return result; } - UInt Length() const - { - return getLength(); - } - - UInt IndexOf(const char * str, UInt id) const // String str + Index indexOf(const char * str, Index id) const // String str { if (id >= getLength()) - return UInt(-1); + return Index(-1); auto findRs = strstr(begin() + id, str); - UInt res = findRs ? findRs - begin() : -1; + Index res = findRs ? findRs - begin() : Index(-1); return res; } - UInt IndexOf(const String & str, UInt id) const + Index indexOf(const String & str, Index id) const { - return IndexOf(str.begin(), id); + return indexOf(str.begin(), id); } - UInt IndexOf(const char * str) const + Index indexOf(const char * str) const { - return IndexOf(str, 0); + return indexOf(str, 0); } - UInt IndexOf(const String & str) const + Index indexOf(const String & str) const { - return IndexOf(str.begin(), 0); + return indexOf(str.begin(), 0); } - UInt IndexOf(char ch, UInt id) const + Index indexOf(char ch, Index id) const { -#if _DEBUG - if (id < 0 || id >= getLength()) - throw "SubString: index out of range."; -#endif - if (!buffer) - return UInt(-1); - for (UInt i = id; i < getLength(); i++) - if (getData()[i] == ch) + const Index length = getLength(); + SLANG_ASSERT(id >= 0 && id <= length); + + if (!m_buffer) + return Index(-1); + + const char* data = getData(); + for (Index i = id; i < length; i++) + if (data[i] == ch) return i; - return UInt(-1); + return Index(-1); } - UInt IndexOf(char ch) const + Index indexOf(char ch) const { - return IndexOf(ch, 0); + return indexOf(ch, 0); } - UInt LastIndexOf(char ch) const - { - for (UInt i = getLength(); i > 0; i--) - if (getData()[i-1] == ch) - return i-1; - return UInt(-1); + Index lastIndexOf(char ch) const + { + const Index length = getLength(); + const char* data = getData(); + + // TODO(JS): If we know Index is signed we can do this a bit more simply + + for (Index i = length; i > 0; i--) + if (data[i - 1] == ch) + return i - 1; + return Index(-1); } - bool StartsWith(const char * str) const // String str + bool startsWith(const char * str) const // String str { - if (!buffer) + if (!m_buffer) return false; - UInt strLen = strlen(str); + Index strLen = Index(::strlen(str)); if (strLen > getLength()) return false; - for (UInt i = 0; i < strLen; i++) - if (str[i] != getData()[i]) + + const char*const data = getData(); + + for (Index i = 0; i < strLen; i++) + if (str[i] != data[i]) return false; return true; } - bool StartsWith(const String & str) const + bool startsWith(const String& str) const { - return StartsWith(str.begin()); + return startsWith(str.begin()); } - bool EndsWith(char const * str) const // String str + bool endsWith(char const * str) const // String str { - if (!buffer) + if (!m_buffer) return false; - UInt strLen = strlen(str); - if (strLen > getLength()) + + const Index strLen = Index(::strlen(str)); + const Index len = getLength(); + + if (strLen > len) return false; - for (UInt i = strLen; i > 0; i--) - if (str[i-1] != getData()[getLength() - strLen + i-1]) + const char* data = getData(); + for (Index i = strLen; i > 0; i--) + if (str[i-1] != data[len - strLen + i-1]) return false; return true; } - bool EndsWith(const String & str) const + bool endsWith(const String & str) const { - return EndsWith(str.begin()); + return endsWith(str.begin()); } - bool Contains(const char * str) const // String str + bool contains(const char * str) const // String str { - if (!buffer) - return false; - return (IndexOf(str) != UInt(-1)) ? true : false; + return m_buffer && indexOf(str) != Index(-1); } - bool Contains(const String & str) const + bool contains(const String & str) const { - return Contains(str.begin()); + return contains(str.begin()); } int GetHashCode() const @@ -731,7 +738,7 @@ namespace Slang UnownedStringSlice getUnownedSlice() const { - return StringRepresentation::asSlice(buffer); + return StringRepresentation::asSlice(m_buffer); } }; @@ -851,7 +858,7 @@ namespace Slang } void Append(const String & str) { - Append(str.Buffer(), str.Length()); + Append(str.getBuffer(), str.getLength()); } void Append(const char * str) { @@ -919,7 +926,7 @@ namespace Slang void Clear() { - buffer = 0; + m_buffer = 0; } }; diff --git a/source/core/slang-writer.cpp b/source/core/slang-writer.cpp index a3222b0d2..2c6f99bf9 100644 --- a/source/core/slang-writer.cpp +++ b/source/core/slang-writer.cpp @@ -66,17 +66,17 @@ ISlangUnknown* BaseWriter::getInterface(const Guid& guid) SLANG_NO_THROW char* SLANG_MCALL AppendBufferWriter::beginAppendBuffer(size_t maxNumChars) { - m_appendBuffer.SetSize(maxNumChars); - return m_appendBuffer.Buffer(); + m_appendBuffer.setCount(maxNumChars); + return m_appendBuffer.getBuffer(); } SLANG_NO_THROW SlangResult SLANG_MCALL AppendBufferWriter::endAppendBuffer(char* buffer, size_t numChars) { - SLANG_ASSERT(m_appendBuffer.Buffer() == buffer && buffer + numChars <= m_appendBuffer.end()); + SLANG_ASSERT(m_appendBuffer.getBuffer() == buffer && buffer + numChars <= m_appendBuffer.end()); // Do the actual write SlangResult res = write(buffer, numChars); // Clear so that buffer can't be written from again without assert - m_appendBuffer.Clear(); + m_appendBuffer.clear(); return res; } @@ -85,17 +85,17 @@ SLANG_NO_THROW SlangResult SLANG_MCALL AppendBufferWriter::endAppendBuffer(char* SLANG_NO_THROW char* SLANG_MCALL CallbackWriter::beginAppendBuffer(size_t maxNumChars) { // Add one so there is always space for end termination, we need for the callback. - m_appendBuffer.SetSize(maxNumChars + 1); - return m_appendBuffer.Buffer(); + m_appendBuffer.setCount(maxNumChars + 1); + return m_appendBuffer.getBuffer(); } SlangResult CallbackWriter::write(const char* chars, size_t numChars) { if (numChars > 0) { - char* appendBuffer = m_appendBuffer.Buffer(); + char* appendBuffer = m_appendBuffer.getBuffer(); // See if it's from an append buffer - if (chars >= appendBuffer && (chars + numChars) < (appendBuffer + m_appendBuffer.Count())) + if (chars >= appendBuffer && (chars + numChars) < (appendBuffer + m_appendBuffer.getCount())) { // Set terminating 0 appendBuffer[(chars + numChars) - appendBuffer] = 0; @@ -105,11 +105,11 @@ SlangResult CallbackWriter::write(const char* chars, size_t numChars) else { // Use the append buffer to add the terminating 0 - m_appendBuffer.SetSize(numChars + 1); - ::memcpy(m_appendBuffer.Buffer(), chars, numChars); + m_appendBuffer.setCount(numChars + 1); + ::memcpy(m_appendBuffer.getBuffer(), chars, numChars); m_appendBuffer[numChars] = 0; - m_callback(m_appendBuffer.Buffer(), (void*)m_data); + m_callback(m_appendBuffer.getBuffer(), (void*)m_data); } } diff --git a/source/core/smart-pointer.h b/source/core/smart-pointer.h index 8ce67e384..aa5c06e02 100644 --- a/source/core/smart-pointer.h +++ b/source/core/smart-pointer.h @@ -5,8 +5,6 @@ #include "hash.h" #include "type-traits.h" -#include <assert.h> - #include "../../slang.h" namespace Slang diff --git a/source/core/stream.cpp b/source/core/stream.cpp index 0fd266e0a..de0a8b8f3 100644 --- a/source/core/stream.cpp +++ b/source/core/stream.cpp @@ -113,11 +113,11 @@ namespace Slang } if (share == Slang::FileShare::None) #pragma warning(suppress:4996) - handle = _wfopen(fileName.ToWString(), mode); + handle = _wfopen(fileName.toWString(), mode); else - handle = _wfsopen(fileName.ToWString(), mode, shFlag); + handle = _wfsopen(fileName.toWString(), mode, shFlag); #else - handle = fopen(fileName.Buffer(), modeMBCS); + handle = fopen(fileName.getBuffer(), modeMBCS); #endif if (!handle) { @@ -228,7 +228,7 @@ namespace Slang pos = offset; break; case Slang::SeekOrigin::End: - pos = Int64(m_contents.Count()) + offset; + pos = Int64(m_contents.getCount()) + offset; break; case Slang::SeekOrigin::Current: pos = Int64(m_position) + offset; @@ -242,7 +242,7 @@ namespace Slang // Clamp to the valid range pos = (pos < 0) ? 0 : pos; - pos = (pos > Int64(m_contents.Count())) ? Int64(m_contents.Count()) : pos; + pos = (pos > Int64(m_contents.getCount())) ? Int64(m_contents.getCount()) : pos; m_position = UInt(pos); } @@ -254,7 +254,7 @@ namespace Slang throw IOException("Cannot read this stream."); } - const Int64 maxRead = Int64(m_contents.Count() - m_position); + const Int64 maxRead = Int64(m_contents.getCount() - m_position); if (maxRead == 0 && length > 0) { @@ -276,13 +276,13 @@ namespace Slang throw IOException("Cannot write this stream."); } - if (m_position == m_contents.Count()) + if (m_position == m_contents.getCount()) { - m_contents.AddRange((const uint8_t*)buffer, UInt(length)); + m_contents.addRange((const uint8_t*)buffer, UInt(length)); } else { - m_contents.InsertRange(m_position, (const uint8_t*)buffer, UInt(length)); + m_contents.insertRange(m_position, (const uint8_t*)buffer, UInt(length)); } m_atEnd = false; diff --git a/source/core/stream.h b/source/core/stream.h index 67a3549e9..618aadbd4 100644 --- a/source/core/stream.h +++ b/source/core/stream.h @@ -79,7 +79,7 @@ namespace Slang m_atEnd(false) {} - UInt m_position; + Index m_position; bool m_atEnd; ///< Happens when a read is done and nothing can be returned because already at end diff --git a/source/core/text-io.cpp b/source/core/text-io.cpp index d0d0a3cc6..1f6b44c92 100644 --- a/source/core/text-io.cpp +++ b/source/core/text-io.cpp @@ -15,7 +15,7 @@ namespace Slang public: virtual void GetBytes(List<char> & result, const String & str) override { - result.AddRange(str.Buffer(), str.Length()); + result.addRange(str.getBuffer(), str.getLength()); } virtual String ToString(const char * bytes, int /*length*/) override { @@ -28,17 +28,17 @@ namespace Slang public: virtual void GetBytes(List<char> & result, const String & str) override { - UInt ptr = 0; - while (ptr < str.Length()) + Index ptr = 0; + while (ptr < str.getLength()) { int codePoint = GetUnicodePointFromUTF8([&](int) { - if (ptr < str.Length()) + if (ptr < str.getLength()) return str[ptr++]; else return '\0'; }); - result.AddRange((char*)&codePoint, 4); + result.addRange((char*)&codePoint, 4); } } virtual String ToString(const char * bytes, int length) override @@ -66,12 +66,12 @@ namespace Slang {} virtual void GetBytes(List<char> & result, const String & str) override { - UInt ptr = 0; - while (ptr < str.Length()) + Index ptr = 0; + while (ptr < str.getLength()) { int codePoint = GetUnicodePointFromUTF8([&](int) { - if (ptr < str.Length()) + if (ptr < str.getLength()) return str[ptr++]; else return '\0'; @@ -82,7 +82,7 @@ namespace Slang count = EncodeUnicodePointToUTF16(buffer, codePoint); else count = EncodeUnicodePointToUTF16Reversed(buffer, codePoint); - result.AddRange((char*)buffer, count * 2); + result.addRange((char*)buffer, count * 2); } } virtual String ToString(const char * bytes, int length) override @@ -148,7 +148,7 @@ namespace Slang } void StreamWriter::Write(const String & str) { - encodingBuffer.Clear(); + encodingBuffer.clear(); StringBuilder sb; String newLine; #ifdef _WIN32 @@ -156,7 +156,7 @@ namespace Slang #else newLine = "\n"; #endif - for (UInt i = 0; i < str.Length(); i++) + for (Index i = 0; i < str.getLength(); i++) { if (str[i] == '\r') sb << newLine; @@ -169,7 +169,7 @@ namespace Slang sb << str[i]; } encoding->GetBytes(encodingBuffer, sb.ProduceString()); - stream->Write(encodingBuffer.Buffer(), encodingBuffer.Count()); + stream->Write(encodingBuffer.getBuffer(), encodingBuffer.getCount()); } void StreamWriter::Write(const char * str) { @@ -207,17 +207,17 @@ namespace Slang Encoding * StreamReader::DetermineEncoding() { - if (buffer.Count() >= 3 && (unsigned char)(buffer[0]) == 0xEF && (unsigned char)(buffer[1]) == 0xBB && (unsigned char)(buffer[2]) == 0xBF) + if (buffer.getCount() >= 3 && (unsigned char)(buffer[0]) == 0xEF && (unsigned char)(buffer[1]) == 0xBB && (unsigned char)(buffer[2]) == 0xBF) { ptr += 3; return Encoding::UTF8; } - else if (*((unsigned short*)(buffer.Buffer())) == 0xFEFF) + else if (*((unsigned short*)(buffer.getBuffer())) == 0xFEFF) { ptr += 2; return Encoding::UTF16; } - else if (*((unsigned short*)(buffer.Buffer())) == 0xFFFE) + else if (*((unsigned short*)(buffer.getBuffer())) == 0xFFFE) { ptr += 2; return Encoding::UTF16Reversed; @@ -225,7 +225,7 @@ namespace Slang else { // find null bytes - if (HasNullBytes(buffer.Buffer(), (int)buffer.Count())) + if (HasNullBytes(buffer.getBuffer(), (int)buffer.getCount())) { return Encoding::UTF16; } @@ -235,22 +235,22 @@ namespace Slang void StreamReader::ReadBuffer() { - buffer.SetSize(4096); - memset(buffer.Buffer(), 0, buffer.Count() * sizeof(buffer[0])); - auto len = stream->Read(buffer.Buffer(), buffer.Count()); - buffer.SetSize((int)len); + buffer.setCount(4096); + memset(buffer.getBuffer(), 0, buffer.getCount() * sizeof(buffer[0])); + auto len = stream->Read(buffer.getBuffer(), buffer.getCount()); + buffer.setCount((int)len); ptr = 0; } char StreamReader::ReadBufferChar() { - if (ptr<buffer.Count()) + if (ptr<buffer.getCount()) { return buffer[ptr++]; } if (!stream->IsEnd()) ReadBuffer(); - if (ptr<buffer.Count()) + if (ptr<buffer.getCount()) { return buffer[ptr++]; } diff --git a/source/core/text-io.h b/source/core/text-io.h index c914e340a..949150777 100644 --- a/source/core/text-io.h +++ b/source/core/text-io.h @@ -273,7 +273,7 @@ namespace Slang RefPtr<Stream> stream; List<char> buffer; Encoding * encoding; - UInt ptr; + Index ptr; char ReadBufferChar(); void ReadBuffer(); @@ -300,7 +300,7 @@ namespace Slang virtual String ReadToEnd(); virtual bool IsEnd() { - return ptr == buffer.Count() && stream->IsEnd(); + return ptr == buffer.getCount() && stream->IsEnd(); } virtual void Close() { diff --git a/source/core/token-reader.cpp b/source/core/token-reader.cpp index bf3294c8e..ea40c9ed9 100644 --- a/source/core/token-reader.cpp +++ b/source/core/token-reader.cpp @@ -44,15 +44,15 @@ namespace Slang void ParseOperators(const String & str, List<Token> & tokens, TokenFlags& tokenFlags, int line, int col, int startPos, String fileName) { - int pos = 0; - while (pos < (int)str.Length()) + Index pos = 0; + while (pos < str.getLength()) { wchar_t curChar = str[pos]; - wchar_t nextChar = (pos < (int)str.Length() - 1) ? str[pos + 1] : '\0'; - wchar_t nextNextChar = (pos < (int)str.Length() - 2) ? str[pos + 2] : '\0'; + wchar_t nextChar = (pos < str.getLength() - 1) ? str[pos + 1] : '\0'; + wchar_t nextNextChar = (pos < str.getLength() - 2) ? str[pos + 2] : '\0'; auto InsertToken = [&](TokenType type, const String & ct) { - tokens.Add(Token(type, ct, line, col + pos, pos + startPos, fileName, tokenFlags)); + tokens.add(Token(type, ct, line, int(col + pos), int(pos + startPos), fileName, tokenFlags)); tokenFlags = 0; }; switch (curChar) @@ -323,7 +323,7 @@ namespace Slang List<Token> TokenizeText(const String & fileName, const String & text) { - int lastPos = 0, pos = 0; + Index lastPos = 0, pos = 0; int line = 1, col = 0; String file = fileName; State state = State::Start; @@ -335,7 +335,7 @@ namespace Slang auto InsertToken = [&](TokenType type) { derivative = LexDerivative::None; - tokenList.Add(Token(type, tokenBuilder.ToString(), tokenLine, tokenCol, pos, file, tokenFlags)); + tokenList.add(Token(type, tokenBuilder.ToString(), tokenLine, tokenCol, int(pos), file, tokenFlags)); tokenFlags = 0; tokenBuilder.Clear(); }; @@ -365,10 +365,10 @@ namespace Slang break; } }; - while (pos <= (int)text.Length()) + while (pos <= text.getLength()) { - char curChar = (pos < (int)text.Length() ? text[pos] : ' '); - char nextChar = (pos < (int)text.Length() - 1) ? text[pos + 1] : '\0'; + char curChar = (pos < text.getLength() ? text[pos] : ' '); + char nextChar = (pos < text.getLength() - 1) ? text[pos + 1] : '\0'; if (lastPos != pos) { if (curChar == '\n') @@ -490,7 +490,7 @@ namespace Slang else { //do token analyze - ParseOperators(tokenBuilder.ToString(), tokenList, tokenFlags, tokenLine, tokenCol, (int)(pos - tokenBuilder.Length()), file); + ParseOperators(tokenBuilder.ToString(), tokenList, tokenFlags, tokenLine, tokenCol, (int)(pos - tokenBuilder.getLength()), file); tokenBuilder.Clear(); state = State::Start; } @@ -674,9 +674,11 @@ namespace Slang { StringBuilder sb; sb << "\""; - for (int i = 0; i < (int)str.Length(); i++) + const Index length = str.getLength(); + const char*const data = str.getBuffer(); + for (Index i = 0; i < length; i++) { - switch (str[i]) + switch (data[i]) { case ' ': sb << "\\s"; @@ -703,7 +705,7 @@ namespace Slang sb << "\\\\"; break; default: - sb << str[i]; + sb << data[i]; break; } } @@ -714,11 +716,13 @@ namespace Slang String UnescapeStringLiteral(String str) { StringBuilder sb; - for (int i = 0; i < (int)str.Length(); i++) + const Index length = str.getLength(); + const char*const data = str.getBuffer(); + for (Index i = 0; i < length; i++) { - if (str[i] == '\\' && i < (int)str.Length() - 1) + if (data[i] == '\\' && i < length - 1) { - switch (str[i + 1]) + switch (data[i + 1]) { case 's': sb << " "; @@ -746,12 +750,12 @@ namespace Slang break; default: i = i - 1; - sb << str[i]; + sb << data[i]; } i++; } else - sb << str[i]; + sb << data[i]; } return sb.ProduceString(); } diff --git a/source/core/token-reader.h b/source/core/token-reader.h index 48391738c..a5b9b3694 100644 --- a/source/core/token-reader.h +++ b/source/core/token-reader.h @@ -189,7 +189,7 @@ namespace Slang } Token ReadToken() { - if (tokenPtr < (int)tokens.Count()) + if (tokenPtr < (int)tokens.getCount()) { auto &rs = tokens[tokenPtr]; tokenPtr++; @@ -199,7 +199,7 @@ namespace Slang } Token NextToken(int offset = 0) { - if (tokenPtr + offset < (int)tokens.Count()) + if (tokenPtr + offset < (int)tokens.getCount()) return tokens[tokenPtr + offset]; else { @@ -210,7 +210,7 @@ namespace Slang } bool LookAhead(String token) { - if (tokenPtr < (int)tokens.Count()) + if (tokenPtr < (int)tokens.getCount()) { auto next = NextToken(); return next.Content == token; @@ -222,7 +222,7 @@ namespace Slang } bool IsEnd() { - return tokenPtr == (int)tokens.Count(); + return tokenPtr == (int)tokens.getCount(); } public: bool IsLegalText() @@ -235,24 +235,24 @@ namespace Slang { List<String> result; StringBuilder sb; - for (int i = 0; i < (int)text.Length(); i++) + for (Index i = 0; i < text.getLength(); i++) { if (text[i] == c) { auto str = sb.ToString(); - if (str.Length() != 0) - result.Add(str); + if (str.getLength() != 0) + result.add(str); sb.Clear(); } else sb << text[i]; } auto lastStr = sb.ToString(); - if (lastStr.Length()) - result.Add(lastStr); + if (lastStr.getLength()) + result.add(lastStr); return result; } } -#endif
\ No newline at end of file +#endif |
