From f65d756bff8d4c5cbc15bd0322a2ae8e6b896a21 Mon Sep 17 00:00:00 2001 From: Ellie Hermaszewska Date: Tue, 29 Oct 2024 14:49:26 +0800 Subject: format * format * Minor test fixes * enable checking cpp format in ci --- source/core/slang-allocator.h | 112 +- source/core/slang-archive-file-system.cpp | 33 +- source/core/slang-archive-file-system.h | 36 +- source/core/slang-array-view.h | 329 +-- source/core/slang-array.h | 395 ++-- source/core/slang-basic.h | 10 +- source/core/slang-blob.cpp | 34 +- source/core/slang-blob.h | 166 +- source/core/slang-byte-encode-util.cpp | 78 +- source/core/slang-byte-encode-util.h | 139 +- source/core/slang-castable.cpp | 8 +- source/core/slang-castable.h | 81 +- source/core/slang-char-encode.cpp | 192 +- source/core/slang-char-encode.h | 57 +- source/core/slang-char-util.cpp | 9 +- source/core/slang-char-util.h | 93 +- source/core/slang-chunked-list.h | 37 +- source/core/slang-com-object.h | 68 +- source/core/slang-command-line.cpp | 12 +- source/core/slang-command-line.h | 113 +- source/core/slang-command-options-writer.cpp | 192 +- source/core/slang-command-options-writer.h | 37 +- source/core/slang-command-options.cpp | 129 +- source/core/slang-command-options.h | 237 ++- source/core/slang-common.h | 289 +-- source/core/slang-compression-system.h | 62 +- source/core/slang-crypto.cpp | 106 +- source/core/slang-crypto.h | 262 ++- source/core/slang-deflate-compression-system.cpp | 54 +- source/core/slang-deflate-compression-system.h | 6 +- source/core/slang-dictionary.h | 1306 ++++++------ source/core/slang-exception.h | 96 +- source/core/slang-file-system.cpp | 362 ++-- source/core/slang-file-system.h | 303 ++- source/core/slang-free-list.cpp | 324 +-- source/core/slang-free-list.h | 236 +-- source/core/slang-func-ptr.h | 47 +- source/core/slang-hash.h | 379 ++-- source/core/slang-hex-dump-util.cpp | 73 +- source/core/slang-hex-dump-util.h | 45 +- source/core/slang-http.cpp | 69 +- source/core/slang-http.h | 127 +- source/core/slang-implicit-directory-collector.cpp | 23 +- source/core/slang-implicit-directory-collector.h | 56 +- source/core/slang-io.cpp | 2093 ++++++++++---------- source/core/slang-io.h | 548 ++--- source/core/slang-linked-list.h | 46 +- source/core/slang-list.h | 994 +++++----- source/core/slang-lz4-compression-system.cpp | 55 +- source/core/slang-lz4-compression-system.h | 6 +- source/core/slang-math.h | 460 ++--- source/core/slang-memory-arena.cpp | 54 +- source/core/slang-memory-arena.h | 279 +-- source/core/slang-memory-file-system.cpp | 61 +- source/core/slang-memory-file-system.h | 93 +- source/core/slang-name-value.cpp | 74 +- source/core/slang-name-value.h | 115 +- source/core/slang-offset-container.cpp | 31 +- source/core/slang-offset-container.h | 336 ++-- source/core/slang-performance-profiler.cpp | 190 +- source/core/slang-performance-profiler.h | 15 +- source/core/slang-persistent-cache.cpp | 29 +- source/core/slang-persistent-cache.h | 6 +- source/core/slang-platform.cpp | 115 +- source/core/slang-platform.h | 277 +-- source/core/slang-process-util.cpp | 27 +- source/core/slang-process-util.h | 18 +- source/core/slang-process.h | 66 +- source/core/slang-random-generator.cpp | 21 +- source/core/slang-random-generator.h | 81 +- source/core/slang-range.h | 37 +- source/core/slang-render-api-util.cpp | 103 +- source/core/slang-render-api-util.h | 55 +- source/core/slang-riff-file-system.cpp | 69 +- source/core/slang-riff-file-system.h | 56 +- source/core/slang-riff.cpp | 143 +- source/core/slang-riff.h | 299 +-- source/core/slang-rtti-info.cpp | 80 +- source/core/slang-rtti-info.h | 256 ++- source/core/slang-rtti-util.cpp | 386 ++-- source/core/slang-rtti-util.h | 80 +- source/core/slang-secure-crt.h | 84 +- source/core/slang-semantic-version.cpp | 76 +- source/core/slang-semantic-version.h | 99 +- source/core/slang-shared-library.cpp | 29 +- source/core/slang-shared-library.h | 65 +- source/core/slang-short-list.h | 772 ++++---- source/core/slang-signal.cpp | 33 +- source/core/slang-signal.h | 14 +- source/core/slang-smart-pointer.h | 518 +++-- source/core/slang-stable-hash.h | 128 +- source/core/slang-std-writers.cpp | 17 +- source/core/slang-std-writers.h | 33 +- source/core/slang-stream.cpp | 162 +- source/core/slang-stream.h | 211 +- source/core/slang-string-escape-util.cpp | 449 +++-- source/core/slang-string-escape-util.h | 110 +- source/core/slang-string-slice-index-map.cpp | 8 +- source/core/slang-string-slice-index-map.h | 50 +- source/core/slang-string-slice-pool.cpp | 39 +- source/core/slang-string-slice-pool.h | 78 +- source/core/slang-string-util.cpp | 184 +- source/core/slang-string-util.h | 276 ++- source/core/slang-string.cpp | 1101 +++++----- source/core/slang-string.h | 1514 +++++++------- source/core/slang-test-tool-util.cpp | 68 +- source/core/slang-test-tool-util.h | 76 +- source/core/slang-text-io.cpp | 137 +- source/core/slang-text-io.h | 161 +- source/core/slang-token-reader.cpp | 1194 +++++------ source/core/slang-token-reader.h | 533 ++--- source/core/slang-type-convert-util.cpp | 37 +- source/core/slang-type-convert-util.h | 7 +- source/core/slang-type-text-util.cpp | 343 ++-- source/core/slang-type-text-util.h | 79 +- source/core/slang-type-traits.h | 82 +- source/core/slang-uint-set.cpp | 42 +- source/core/slang-uint-set.h | 114 +- source/core/slang-virtual-object-pool.h | 8 +- source/core/slang-writer.cpp | 39 +- source/core/slang-writer.h | 161 +- source/core/slang-zip-file-system.cpp | 250 ++- source/core/slang-zip-file-system.h | 9 +- source/core/unix/slang-unix-process.cpp | 152 +- source/core/windows/slang-win-process.cpp | 213 +- 125 files changed, 13100 insertions(+), 11131 deletions(-) (limited to 'source/core') diff --git a/source/core/slang-allocator.h b/source/core/slang-allocator.h index 8942f993b..03cfabe40 100644 --- a/source/core/slang-allocator.h +++ b/source/core/slang-allocator.h @@ -5,89 +5,77 @@ #include #ifdef _MSC_VER -# include +#include #endif #include namespace Slang { - inline void* alignedAllocate(size_t size, size_t alignment) - { +inline void* alignedAllocate(size_t size, size_t alignment) +{ #ifdef _MSC_VER - return _aligned_malloc(size, alignment); + return _aligned_malloc(size, alignment); #elif defined(__CYGWIN__) - return aligned_alloc(alignment, size); + return aligned_alloc(alignment, size); #else - void* rs = nullptr; - int succ = posix_memalign(&rs, alignment, size); - return (succ == 0) ? rs : nullptr; + void* rs = nullptr; + int succ = posix_memalign(&rs, alignment, size); + return (succ == 0) ? rs : nullptr; #endif - } +} - inline void alignedDeallocate(void* ptr) - { +inline void alignedDeallocate(void* ptr) +{ #ifdef _MSC_VER - _aligned_free(ptr); + _aligned_free(ptr); #else - free(ptr); + free(ptr); #endif - } +} - class StandardAllocator - { - public: - // not really called - void* allocate(size_t size) - { - return ::malloc(size); - } - void deallocate(void * ptr) - { - return ::free(ptr); - } - }; +class StandardAllocator +{ +public: + // not really called + void* allocate(size_t size) { return ::malloc(size); } + void deallocate(void* ptr) { return ::free(ptr); } +}; - template - class AlignedAllocator - { - public: - void* allocate(size_t size) - { - return alignedAllocate(size, ALIGNMENT); - } - void deallocate(void * ptr) - { - return alignedDeallocate(ptr); - } - }; +template +class AlignedAllocator +{ +public: + void* allocate(size_t size) { return alignedAllocate(size, ALIGNMENT); } + void deallocate(void* ptr) { return alignedDeallocate(ptr); } +}; - template - class AllocateMethod +template +class AllocateMethod +{ +public: + static inline T* allocateArray(Index count) { - public: - static inline T* allocateArray(Index count) + TAllocator allocator; + T* rs = (T*)allocator.allocate(count * sizeof(T)); + if (!std::is_trivially_constructible::value) { - TAllocator allocator; - T* rs = (T*)allocator.allocate(count * sizeof(T)); - if (!std::is_trivially_constructible::value) - { - for (Index i = 0; i < count; i++) - new (rs + i) T(); - } - return rs; + for (Index i = 0; i < count; i++) + new (rs + i) T(); } - static inline void deallocateArray(T* ptr, Index count) + return rs; + } + static inline void deallocateArray(T* ptr, Index count) + { + TAllocator allocator; + if (!std::is_trivially_destructible::value) { - TAllocator allocator; - if (!std::is_trivially_destructible::value) - { - for (Index i = 0; i < count; i++) - ptr[i].~T(); - } - allocator.deallocate(ptr); + for (Index i = 0; i < count; i++) + ptr[i].~T(); } - }; + allocator.deallocate(ptr); + } +}; #if 0 template @@ -104,6 +92,6 @@ namespace Slang } }; #endif -} +} // namespace Slang #endif diff --git a/source/core/slang-archive-file-system.cpp b/source/core/slang-archive-file-system.cpp index e219fcbb5..9513e6372 100644 --- a/source/core/slang-archive-file-system.cpp +++ b/source/core/slang-archive-file-system.cpp @@ -1,29 +1,28 @@ #include "slang-archive-file-system.h" +#include "../core/slang-castable.h" +#include "slang-blob.h" #include "slang-com-helper.h" #include "slang-com-ptr.h" - -#include "../core/slang-castable.h" - #include "slang-io.h" -#include "slang-string-util.h" -#include "slang-blob.h" - #include "slang-riff-file-system.h" +#include "slang-string-util.h" // Compression systems #include "slang-deflate-compression-system.h" #include "slang-lz4-compression-system.h" // Zip file system -#include "slang-zip-file-system.h" - #include "slang-riff.h" +#include "slang-zip-file-system.h" namespace Slang { -SlangResult loadArchiveFileSystem(const void* data, size_t dataSizeInBytes, ComPtr& outFileSystem) +SlangResult loadArchiveFileSystem( + const void* data, + size_t dataSizeInBytes, + ComPtr& outFileSystem) { ComPtr fileSystem; if (ZipFileSystem::isArchive(data, dataSizeInBytes)) @@ -34,7 +33,7 @@ SlangResult loadArchiveFileSystem(const void* data, size_t dataSizeInBytes, ComP else if (RiffFileSystem::isArchive(data, dataSizeInBytes)) { // It's riff contained (Slang specific) - fileSystem = new RiffFileSystem(nullptr); + fileSystem = new RiffFileSystem(nullptr); } else { @@ -52,26 +51,28 @@ SlangResult loadArchiveFileSystem(const void* data, size_t dataSizeInBytes, ComP outFileSystem = fileSystem; return SLANG_OK; } - -SlangResult createArchiveFileSystem(SlangArchiveType type, ComPtr& outFileSystem) + +SlangResult createArchiveFileSystem( + SlangArchiveType type, + ComPtr& outFileSystem) { switch (type) { - case SLANG_ARCHIVE_TYPE_ZIP: + case SLANG_ARCHIVE_TYPE_ZIP: { return ZipFileSystem::create(outFileSystem); } - case SLANG_ARCHIVE_TYPE_RIFF: + case SLANG_ARCHIVE_TYPE_RIFF: { outFileSystem = new RiffFileSystem(nullptr); return SLANG_OK; } - case SLANG_ARCHIVE_TYPE_RIFF_DEFLATE: + case SLANG_ARCHIVE_TYPE_RIFF_DEFLATE: { outFileSystem = new RiffFileSystem(DeflateCompressionSystem::getSingleton()); return SLANG_OK; } - case SLANG_ARCHIVE_TYPE_RIFF_LZ4: + case SLANG_ARCHIVE_TYPE_RIFF_LZ4: { outFileSystem = new RiffFileSystem(LZ4CompressionSystem::getSingleton()); return SLANG_OK; diff --git a/source/core/slang-archive-file-system.h b/source/core/slang-archive-file-system.h index 13b226019..25bac0812 100644 --- a/source/core/slang-archive-file-system.h +++ b/source/core/slang-archive-file-system.h @@ -2,9 +2,7 @@ #define SLANG_CORE_ARCHIVE_FILE_SYSTEM_H #include "slang-basic.h" - #include "slang-com-ptr.h" - #include "slang-compression-system.h" namespace Slang @@ -12,20 +10,32 @@ namespace Slang class IArchiveFileSystem : public ISlangCastable { - SLANG_COM_INTERFACE(0x5c565aac, 0xe834, 0x41fc, { 0x8b, 0xb, 0x7d, 0x4c, 0xf3, 0x8b, 0x89, 0x50 }); - - /// Loads an archive. - SLANG_NO_THROW virtual SlangResult SLANG_MCALL loadArchive(const void* archive, size_t archiveSizeInBytes) = 0; - /// Get as an archive (that can be saved to disk) - /// NOTE! If the blob is not owned, it's contents can be invalidated by any call to a method of the file system or loss of scope - SLANG_NO_THROW virtual SlangResult SLANG_MCALL storeArchive(bool blobOwnsContent, ISlangBlob** outBlob) = 0; - /// Set the compression - used for any subsequent items added + SLANG_COM_INTERFACE( + 0x5c565aac, + 0xe834, + 0x41fc, + {0x8b, 0xb, 0x7d, 0x4c, 0xf3, 0x8b, 0x89, 0x50}); + + /// Loads an archive. + SLANG_NO_THROW virtual SlangResult SLANG_MCALL + loadArchive(const void* archive, size_t archiveSizeInBytes) = 0; + /// Get as an archive (that can be saved to disk) + /// NOTE! If the blob is not owned, it's contents can be invalidated by any call to a method of + /// the file system or loss of scope + SLANG_NO_THROW virtual SlangResult SLANG_MCALL + storeArchive(bool blobOwnsContent, ISlangBlob** outBlob) = 0; + /// Set the compression - used for any subsequent items added SLANG_NO_THROW virtual void SLANG_MCALL setCompressionStyle(const CompressionStyle& style) = 0; }; -SlangResult loadArchiveFileSystem(const void* data, size_t dataSizeInBytes, ComPtr& outFileSystem); -SlangResult createArchiveFileSystem(SlangArchiveType type, ComPtr& outFileSystem); +SlangResult loadArchiveFileSystem( + const void* data, + size_t dataSizeInBytes, + ComPtr& outFileSystem); +SlangResult createArchiveFileSystem( + SlangArchiveType type, + ComPtr& outFileSystem); -} +} // namespace Slang #endif diff --git a/source/core/slang-array-view.h b/source/core/slang-array-view.h index 50270e0a0..21b6ce113 100644 --- a/source/core/slang-array-view.h +++ b/source/core/slang-array-view.h @@ -6,222 +6,225 @@ namespace Slang { - // !!!!!!!!!!!!!!!!!!!!!!!!!!!!! ConstArrayView !!!!!!!!!!!!!!!!!!!!!!!!!!!!! +// !!!!!!!!!!!!!!!!!!!!!!!!!!!!! ConstArrayView !!!!!!!!!!!!!!!!!!!!!!!!!!!!! - template - class ConstArrayView - { - public: - typedef ConstArrayView ThisType; +template +class ConstArrayView +{ +public: + typedef ConstArrayView ThisType; - SLANG_FORCE_INLINE const T* begin() const { return m_buffer; } - - SLANG_FORCE_INLINE const T* end() const { return m_buffer + m_count; } - - SLANG_FORCE_INLINE Count getCount() const { return m_count; } + SLANG_FORCE_INLINE const T* begin() const { return m_buffer; } - SLANG_FORCE_INLINE const T& operator [](Index idx) const - { - SLANG_ASSERT(idx >= 0 && idx < m_count); - return m_buffer[idx]; - } - - SLANG_FORCE_INLINE const T* getBuffer() const { return m_buffer; } - - template - Index indexOf(const T2& val) const - { - for (Index i = 0; i < m_count; i++) - { - if (m_buffer[i] == val) - return i; - } - return -1; - } + SLANG_FORCE_INLINE const T* end() const { return m_buffer + m_count; } - template - Index lastIndexOf(const T2& val) const - { - for (Index i = m_count - 1; i >= 0; i--) - { - if (m_buffer[i] == val) - return i; - } - return -1; - } + SLANG_FORCE_INLINE Count getCount() const { return m_count; } - template - Index findFirstIndex(const Func& predicate) const - { - for (Index i = 0; i < m_count; i++) - { - if (predicate(m_buffer[i])) - return i; - } - return -1; - } + SLANG_FORCE_INLINE const T& operator[](Index idx) const + { + SLANG_ASSERT(idx >= 0 && idx < m_count); + return m_buffer[idx]; + } - template - Index findLastIndex(const Func& predicate) const - { - for (Index i = m_count - 1; i >= 0; i--) - { - if (predicate(m_buffer[i])) - return i; - } - return -1; - } + SLANG_FORCE_INLINE const T* getBuffer() const { return m_buffer; } - bool containsMemory(const ThisType& rhs) const + template + Index indexOf(const T2& val) const + { + for (Index i = 0; i < m_count; i++) { - return rhs.getBuffer() >= getBuffer() && rhs.end() <= end(); + if (m_buffer[i] == val) + return i; } + return -1; + } - bool operator==(const ThisType& rhs) const + template + Index lastIndexOf(const T2& val) const + { + for (Index i = m_count - 1; i >= 0; i--) { - if (&rhs == this) - { - return true; - } - const Count count = getCount(); - if (count != rhs.getCount()) - { - return false; - } - const T* thisEle = getBuffer(); - const T* rhsEle = rhs.getBuffer(); - for (Index i = 0; i < count; ++i) - { - if (thisEle[i] != rhsEle[i]) - { - return false; - } - } - return true; + if (m_buffer[i] == val) + return i; } - SLANG_FORCE_INLINE bool operator!=(const ThisType& rhs) const { return !(*this == rhs); } + return -1; + } - ThisType head(Index index) const + template + Index findFirstIndex(const Func& predicate) const + { + for (Index i = 0; i < m_count; i++) { - SLANG_ASSERT(index >= 0 && index <= m_count); - return ThisType(m_buffer, index); + if (predicate(m_buffer[i])) + return i; } - ThisType tail(Index index) const + return -1; + } + + template + Index findLastIndex(const Func& predicate) const + { + for (Index i = m_count - 1; i >= 0; i--) { - SLANG_ASSERT(index >= 0 && index <= m_count); - return ThisType(m_buffer + index, m_count - index); + if (predicate(m_buffer[i])) + return i; } + return -1; + } - ConstArrayView() : - m_buffer(nullptr), - m_count(0) + bool containsMemory(const ThisType& rhs) const + { + return rhs.getBuffer() >= getBuffer() && rhs.end() <= end(); + } + + bool operator==(const ThisType& rhs) const + { + if (&rhs == this) { + return true; } - - ConstArrayView(const T* buffer, Count count) : - m_buffer(const_cast(buffer)), - m_count(count) + const Count count = getCount(); + if (count != rhs.getCount()) { + return false; } - - protected: - ConstArrayView(T* buffer, Count count) : - m_buffer(buffer), - m_count(count) + const T* thisEle = getBuffer(); + const T* rhsEle = rhs.getBuffer(); + for (Index i = 0; i < count; ++i) { + if (thisEle[i] != rhsEle[i]) + { + return false; + } } + return true; + } + SLANG_FORCE_INLINE bool operator!=(const ThisType& rhs) const { return !(*this == rhs); } - T* m_buffer; ///< Note that this isn't const, as is used for derived class ArrayView also - Count m_count; - }; + ThisType head(Index index) const + { + SLANG_ASSERT(index >= 0 && index <= m_count); + return ThisType(m_buffer, index); + } + ThisType tail(Index index) const + { + SLANG_ASSERT(index >= 0 && index <= m_count); + return ThisType(m_buffer + index, m_count - index); + } - template - ConstArrayView makeConstArrayViewSingle(const T& obj) + ConstArrayView() + : m_buffer(nullptr), m_count(0) { - return ConstArrayView(&obj, 1); - } + } - template - ConstArrayView makeConstArrayView(const T* buffer, Count count) + ConstArrayView(const T* buffer, Count count) + : m_buffer(const_cast(buffer)), m_count(count) { - return ConstArrayView(buffer, count); } - template - ConstArrayView makeConstArrayView(const T (&arr)[N]) +protected: + ConstArrayView(T* buffer, Count count) + : m_buffer(buffer), m_count(count) { - return ConstArrayView(arr, Index(N)); } + T* m_buffer; ///< Note that this isn't const, as is used for derived class ArrayView also + Count m_count; +}; - // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ArrayView !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! +template +ConstArrayView makeConstArrayViewSingle(const T& obj) +{ + return ConstArrayView(&obj, 1); +} - template - class ArrayView: public ConstArrayView - { - public: - typedef ArrayView ThisType; +template +ConstArrayView makeConstArrayView(const T* buffer, Count count) +{ + return ConstArrayView(buffer, count); +} - typedef ConstArrayView Super; - - using Super::m_buffer; - using Super::m_count; +template +ConstArrayView makeConstArrayView(const T (&arr)[N]) +{ + return ConstArrayView(arr, Index(N)); +} - using Super::begin; - T* begin() { return m_buffer; } - using Super::end; - T* end() { return m_buffer + m_count; } - - using Super::head; - using Super::tail; +// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ArrayView !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! - using Super::operator[]; - inline T& operator [](Index idx) - { - SLANG_ASSERT(idx >= 0 && idx < m_count); - return m_buffer[idx]; - } +template +class ArrayView : public ConstArrayView +{ +public: + typedef ArrayView ThisType; - using Super::getBuffer; - inline T* getBuffer() { return m_buffer; } + typedef ConstArrayView Super; - ThisType head(Index index) - { - SLANG_ASSERT(index >= 0 && index <= m_count); - return ThisType(m_buffer, index); - } - ThisType tail(Index index) - { - SLANG_ASSERT(index >= 0 && index <= m_count); - return ThisType(m_buffer + index, m_count - index); - } + using Super::m_buffer; + using Super::m_count; + + using Super::begin; + T* begin() { return m_buffer; } - T& getLast() { return m_buffer[m_count - 1]; } + using Super::end; + T* end() { return m_buffer + m_count; } - ArrayView() : Super() {} - ArrayView(T* buffer, Index size) :Super(buffer, size) {} - }; + using Super::head; + using Super::tail; - template - ArrayView makeArrayViewSingle(T& obj) + using Super::operator[]; + inline T& operator[](Index idx) { - return ArrayView(&obj, 1); - } - - template - ArrayView makeArrayView(T* buffer, Count count) + SLANG_ASSERT(idx >= 0 && idx < m_count); + return m_buffer[idx]; + } + + using Super::getBuffer; + inline T* getBuffer() { return m_buffer; } + + ThisType head(Index index) { - return ArrayView(buffer, count); + SLANG_ASSERT(index >= 0 && index <= m_count); + return ThisType(m_buffer, index); } + ThisType tail(Index index) + { + SLANG_ASSERT(index >= 0 && index <= m_count); + return ThisType(m_buffer + index, m_count - index); + } + + T& getLast() { return m_buffer[m_count - 1]; } - template - ArrayView makeArrayView(T (&arr)[N]) + ArrayView() + : Super() { - return ArrayView(arr, Count(N)); } + ArrayView(T* buffer, Index size) + : Super(buffer, size) + { + } +}; + +template +ArrayView makeArrayViewSingle(T& obj) +{ + return ArrayView(&obj, 1); +} +template +ArrayView makeArrayView(T* buffer, Count count) +{ + return ArrayView(buffer, count); +} +template +ArrayView makeArrayView(T (&arr)[N]) +{ + return ArrayView(arr, Count(N)); } + +} // namespace Slang + #endif diff --git a/source/core/slang-array.h b/source/core/slang-array.h index d24ff0970..5c2fefc26 100644 --- a/source/core/slang-array.h +++ b/source/core/slang-array.h @@ -1,197 +1,220 @@ #ifndef SLANG_CORE_ARRAY_H #define SLANG_CORE_ARRAY_H -#include "slang-exception.h" #include "slang-array-view.h" +#include "slang-exception.h" namespace Slang { - /* An array container with fixed maximum size defined by COUNT. */ - template - class Array - { - public: - 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; } - - inline Index getCapacity() const { return COUNT; } - inline Index getCount() const { return m_count; } - inline const T& getFirst() const - { - SLANG_ASSERT(m_count > 0); - return m_buffer[0]; - } - inline T& getFirst() - { - SLANG_ASSERT(m_count > 0); - return m_buffer[0]; - } - inline const T& getLast() const - { - SLANG_ASSERT(m_count > 0); - return m_buffer[m_count - 1]; - } - inline T& getLast() - { - SLANG_ASSERT(m_count > 0); - return m_buffer[m_count - 1]; - } - inline void setCount(Index newCount) - { - SLANG_ASSERT(newCount >= 0 && newCount <= COUNT); - m_count = newCount; - } - inline void add(const T& item) - { - SLANG_ASSERT(m_count < COUNT); - m_buffer[m_count++] = item; - } - inline void add(T&& item) - { - SLANG_ASSERT(m_count < COUNT); - m_buffer[m_count++] = _Move(item); - } - - inline const T& operator [](Index idx) const - { - SLANG_ASSERT(idx >= 0 && idx < m_count); - return m_buffer[idx]; - } - inline T& operator [](Index idx) - { - SLANG_ASSERT(idx >= 0 && idx < m_count); - return m_buffer[idx]; - } - - inline const T* getBuffer() const { return m_buffer; } - inline T* getBuffer() { return m_buffer; } - - inline void clear() { m_count = 0; } - - template - Index indexOf(const T2& val) const { return getView().indexOf(val); } - template - Index lastIndexOf(const T2& val) const { return getView().lastIndexOf(val); } - template - Index findFirstIndex(const Func& predicate) const { return getView().findFirstIndex(predicate); } - template - Index findLastIndex(const Func& predicate) const { return getView().findLastIndex(predicate); } - - inline ConstArrayView getView() const { return ConstArrayView(m_buffer, m_count); } - inline ConstArrayView getView(Index start, Index count) const - { - SLANG_ASSERT(start >= 0 && count >= 0); - SLANG_ASSERT(start <= m_count && start + count < m_count); - return ConstArrayView(m_buffer + start, count); - } - - inline ArrayView getView() { return ArrayView(m_buffer, m_count); } - inline ArrayView getView(Index start, Index count) - { - SLANG_ASSERT(start >= 0 && count >= 0); - SLANG_ASSERT(start <= m_count && start + count < m_count); - return ArrayView(m_buffer + start, count); - } - - private: - T m_buffer[COUNT]; - Index m_count = 0; - }; - - template - class Array - { - public: - T* begin() { return nullptr; } - const T* begin() const { return nullptr; } - - const T* end() const { return nullptr; } - T* end() { return nullptr; } - - inline Index getCapacity() const { return 0; } - inline Index getCount() const { return 0; } - inline void setCount(Index newCount) - { - SLANG_ASSERT(newCount == 0); - } - inline const T* getBuffer() const { return nullptr; } - inline T* getBuffer() { return nullptr; } - inline void clear() {} - - template - Index indexOf(const T2& val) const { return getView().indexOf(val); } - template - Index lastIndexOf(const T2& val) const { return getView().lastIndexOf(val); } - template - Index findFirstIndex(const Func& predicate) const { return getView().findFirstIndex(predicate); } - template - Index findLastIndex(const Func& predicate) const { return getView().findLastIndex(predicate); } - - inline ConstArrayView getView() const { return ConstArrayView(nullptr, 0); } - inline ConstArrayView getView(Index start, Index count) const - { - SLANG_ASSERT(start == 0 && count == 0); - return ConstArrayView(nullptr, 0); - } - - inline ArrayView getView() { return ArrayView(nullptr, 0); } - inline ArrayView getView(Index start, Index count) - { - SLANG_ASSERT(start == 0 && count == 0); - return ArrayView(nullptr, 0); - } - }; - - template - struct FirstType - { - typedef T Type; - }; - - - template - void insertArray(Array&) {} - - template - void insertArray(Array& arr, const T& val, TArgs... args) - { - arr.add(val); - insertArray(arr, args...); - } - - template - auto makeArray(TArgs ...args) -> Array::Type, sizeof...(args)> - { - Array::Type, Index(sizeof...(args))> rs; - insertArray::Type>(rs, args...); - return rs; - } - - template - auto makeArray() -> Array - { - return Array(); - } - - - template - void addToList(TList&) - { - } - template - void addToList(TList& list, T node) - { - list.add(node); - } - template - void addToList(TList& list, T node, TArgs ... args) - { - list.add(node); - addToList(list, args...); +/* An array container with fixed maximum size defined by COUNT. */ +template +class Array +{ +public: + 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; } + + inline Index getCapacity() const { return COUNT; } + inline Index getCount() const { return m_count; } + inline const T& getFirst() const + { + SLANG_ASSERT(m_count > 0); + return m_buffer[0]; + } + inline T& getFirst() + { + SLANG_ASSERT(m_count > 0); + return m_buffer[0]; + } + inline const T& getLast() const + { + SLANG_ASSERT(m_count > 0); + return m_buffer[m_count - 1]; + } + inline T& getLast() + { + SLANG_ASSERT(m_count > 0); + return m_buffer[m_count - 1]; + } + inline void setCount(Index newCount) + { + SLANG_ASSERT(newCount >= 0 && newCount <= COUNT); + m_count = newCount; + } + inline void add(const T& item) + { + SLANG_ASSERT(m_count < COUNT); + m_buffer[m_count++] = item; + } + inline void add(T&& item) + { + SLANG_ASSERT(m_count < COUNT); + m_buffer[m_count++] = _Move(item); + } + + inline const T& operator[](Index idx) const + { + SLANG_ASSERT(idx >= 0 && idx < m_count); + return m_buffer[idx]; + } + inline T& operator[](Index idx) + { + SLANG_ASSERT(idx >= 0 && idx < m_count); + return m_buffer[idx]; + } + + inline const T* getBuffer() const { return m_buffer; } + inline T* getBuffer() { return m_buffer; } + + inline void clear() { m_count = 0; } + + template + Index indexOf(const T2& val) const + { + return getView().indexOf(val); + } + template + Index lastIndexOf(const T2& val) const + { + return getView().lastIndexOf(val); + } + template + Index findFirstIndex(const Func& predicate) const + { + return getView().findFirstIndex(predicate); + } + template + Index findLastIndex(const Func& predicate) const + { + return getView().findLastIndex(predicate); + } + + inline ConstArrayView getView() const { return ConstArrayView(m_buffer, m_count); } + inline ConstArrayView getView(Index start, Index count) const + { + SLANG_ASSERT(start >= 0 && count >= 0); + SLANG_ASSERT(start <= m_count && start + count < m_count); + return ConstArrayView(m_buffer + start, count); + } + + inline ArrayView getView() { return ArrayView(m_buffer, m_count); } + inline ArrayView getView(Index start, Index count) + { + SLANG_ASSERT(start >= 0 && count >= 0); + SLANG_ASSERT(start <= m_count && start + count < m_count); + return ArrayView(m_buffer + start, count); } + +private: + T m_buffer[COUNT]; + Index m_count = 0; +}; + +template +class Array +{ +public: + T* begin() { return nullptr; } + const T* begin() const { return nullptr; } + + const T* end() const { return nullptr; } + T* end() { return nullptr; } + + inline Index getCapacity() const { return 0; } + inline Index getCount() const { return 0; } + inline void setCount(Index newCount) { SLANG_ASSERT(newCount == 0); } + inline const T* getBuffer() const { return nullptr; } + inline T* getBuffer() { return nullptr; } + inline void clear() {} + + template + Index indexOf(const T2& val) const + { + return getView().indexOf(val); + } + template + Index lastIndexOf(const T2& val) const + { + return getView().lastIndexOf(val); + } + template + Index findFirstIndex(const Func& predicate) const + { + return getView().findFirstIndex(predicate); + } + template + Index findLastIndex(const Func& predicate) const + { + return getView().findLastIndex(predicate); + } + + inline ConstArrayView getView() const { return ConstArrayView(nullptr, 0); } + inline ConstArrayView getView(Index start, Index count) const + { + SLANG_ASSERT(start == 0 && count == 0); + return ConstArrayView(nullptr, 0); + } + + inline ArrayView getView() { return ArrayView(nullptr, 0); } + inline ArrayView getView(Index start, Index count) + { + SLANG_ASSERT(start == 0 && count == 0); + return ArrayView(nullptr, 0); + } +}; + +template +struct FirstType +{ + typedef T Type; +}; + + +template +void insertArray(Array&) +{ +} + +template +void insertArray(Array& arr, const T& val, TArgs... args) +{ + arr.add(val); + insertArray(arr, args...); +} + +template +auto makeArray(TArgs... args) -> Array::Type, sizeof...(args)> +{ + Array::Type, Index(sizeof...(args))> rs; + insertArray::Type>(rs, args...); + return rs; +} + +template +auto makeArray() -> Array +{ + return Array(); +} + + +template +void addToList(TList&) +{ +} +template +void addToList(TList& list, T node) +{ + list.add(node); +} +template +void addToList(TList& list, T node, TArgs... args) +{ + list.add(node); + addToList(list, args...); } +} // namespace Slang #endif diff --git a/source/core/slang-basic.h b/source/core/slang-basic.h index 5387af4aa..d37782160 100644 --- a/source/core/slang-basic.h +++ b/source/core/slang-basic.h @@ -1,14 +1,14 @@ #ifndef SLANG_CORE_BASIC_H #define SLANG_CORE_BASIC_H -#include "slang-common.h" -#include "slang-math.h" -#include "slang-string.h" #include "slang-array.h" +#include "slang-common.h" +#include "slang-dictionary.h" +#include "slang-exception.h" #include "slang-list.h" +#include "slang-math.h" #include "slang-short-list.h" #include "slang-smart-pointer.h" -#include "slang-exception.h" -#include "slang-dictionary.h" +#include "slang-string.h" #endif diff --git a/source/core/slang-blob.cpp b/source/core/slang-blob.cpp index 19a4281bd..ea4f4b6c0 100644 --- a/source/core/slang-blob.cpp +++ b/source/core/slang-blob.cpp @@ -1,13 +1,13 @@ #include "slang-blob.h" -namespace Slang { +namespace Slang +{ /* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! BlobBase !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */ ISlangUnknown* BlobBase::getInterface(const Guid& guid) { - if (guid == ISlangUnknown::getTypeGuid() || - guid == ISlangBlob::getTypeGuid()) + if (guid == ISlangUnknown::getTypeGuid() || guid == ISlangBlob::getTypeGuid()) { return static_cast(this); } @@ -41,12 +41,11 @@ void StringBlob::_setUniqueRep(StringRepresentation* uniqueRep) m_uniqueRep = uniqueRep; - m_slice = uniqueRep ? - UnownedTerminatedStringSlice(uniqueRep->getData(), uniqueRep->getLength()) : - UnownedTerminatedStringSlice(); + m_slice = uniqueRep ? UnownedTerminatedStringSlice(uniqueRep->getData(), uniqueRep->getLength()) + : UnownedTerminatedStringSlice(); } -/* static */StringRepresentation* StringBlob::_createUniqueCopy(StringRepresentation* rep) +/* static */ StringRepresentation* StringBlob::_createUniqueCopy(StringRepresentation* rep) { if (rep) { @@ -75,7 +74,7 @@ void StringBlob::_setWithMove(StringRepresentation* rep) if (rep && !rep->isUniquelyReferenced()) { _setUniqueRep(_createUniqueCopy(rep)); - // We need to release a ref as rep is passed in with the 'current' ref count + // We need to release a ref as rep is passed in with the 'current' ref count rep->releaseReference(); } else @@ -84,7 +83,7 @@ void StringBlob::_setWithMove(StringRepresentation* rep) } } -/* static */ComPtr StringBlob::create(const UnownedStringSlice& slice) +/* static */ ComPtr StringBlob::create(const UnownedStringSlice& slice) { StringRepresentation* rep = nullptr; if (slice.getLength()) @@ -93,27 +92,27 @@ void StringBlob::_setWithMove(StringRepresentation* rep) } auto blob = new StringBlob; - + // rep must be unique at this point blob->_setUniqueRep(rep); return ComPtr(blob); } -/* static */ComPtr StringBlob::create(const String& in) +/* static */ ComPtr StringBlob::create(const String& in) { auto blob = new StringBlob; blob->_setWithCopy(in.getStringRepresentation()); return ComPtr(blob); } -/* static */ComPtr StringBlob::moveCreate(String& in) +/* static */ ComPtr StringBlob::moveCreate(String& in) { auto blob = new StringBlob; blob->_setWithMove(in.detachStringRepresentation()); return ComPtr(blob); } -/* static */ComPtr StringBlob::moveCreate(String&& in) +/* static */ ComPtr StringBlob::moveCreate(String&& in) { auto blob = new StringBlob; blob->_setWithMove(in.detachStringRepresentation()); @@ -167,7 +166,7 @@ void* RawBlob::getObject(const Guid& guid) // If the data has 0 termination, we can return the pointer if (guid == SlangTerminatedChars::getTypeGuid() && m_data.isTerminated()) { - return (char*)m_data.getData(); + return (char*)m_data.getData(); } return nullptr; } @@ -185,7 +184,7 @@ void* ScopeBlob::castAs(const SlangUUID& guid) return obj; } - // If the contained thing is castable, ask it + // If the contained thing is castable, ask it if (m_castable) { return m_castable->castAs(guid); @@ -225,7 +224,7 @@ void* ListBlob::getObject(const Guid& guid) /* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! StaticBlob !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */ -SlangResult StaticBlob::queryInterface(SlangUUID const& guid, void** outObject) +SlangResult StaticBlob::queryInterface(SlangUUID const& guid, void** outObject) { if (auto intf = getInterface(guid)) { @@ -246,8 +245,7 @@ void* StaticBlob::castAs(const SlangUUID& guid) ISlangUnknown* StaticBlob::getInterface(const Guid& guid) { - if (guid == ISlangUnknown::getTypeGuid() || - guid == ISlangBlob::getTypeGuid()) + if (guid == ISlangUnknown::getTypeGuid() || guid == ISlangBlob::getTypeGuid()) { return static_cast(this); } diff --git a/source/core/slang-blob.h b/source/core/slang-blob.h index 4df8f0db6..af3206fb5 100644 --- a/source/core/slang-blob.h +++ b/source/core/slang-blob.h @@ -1,22 +1,20 @@ #ifndef SLANG_CORE_BLOB_H #define SLANG_CORE_BLOB_H -#include "slang.h" - -#include "slang-string.h" -#include "slang-list.h" - -#include - +#include "../core/slang-com-object.h" #include "slang-com-helper.h" #include "slang-com-ptr.h" +#include "slang-list.h" +#include "slang-string.h" +#include "slang.h" -#include "../core/slang-com-object.h" +#include -namespace Slang { +namespace Slang +{ /** Base class for simple blobs. -*/ + */ class BlobBase : public ISlangBlob, public ICastable, public ComBaseObject { public: @@ -33,53 +31,57 @@ protected: /** A blob that uses a `StringRepresentation` for its storage. -By design the StringBlob owns a unique reference to the StringRepresentation. +By design the StringBlob owns a unique reference to the StringRepresentation. This is because StringBlob, implements an interface which should work across threads. */ class StringBlob : public BlobBase { public: - SLANG_CLASS_GUID(0xf7e0e93c, 0xde70, 0x4531, { 0x9c, 0x9f, 0xdd, 0xa3, 0xf6, 0xc6, 0xc0, 0xdd }); + SLANG_CLASS_GUID(0xf7e0e93c, 0xde70, 0x4531, {0x9c, 0x9f, 0xdd, 0xa3, 0xf6, 0xc6, 0xc0, 0xdd}); // ICastable virtual SLANG_NO_THROW void* SLANG_MCALL castAs(const SlangUUID& guid) SLANG_OVERRIDE; // ISlangBlob - SLANG_NO_THROW void const* SLANG_MCALL getBufferPointer() SLANG_OVERRIDE { return m_slice.begin(); } + SLANG_NO_THROW void const* SLANG_MCALL getBufferPointer() SLANG_OVERRIDE + { + return m_slice.begin(); + } SLANG_NO_THROW size_t SLANG_MCALL getBufferSize() SLANG_OVERRIDE { return m_slice.getLength(); } - /// Since in is not being moved will *always* create a new representation, unless the in is empty + /// Since in is not being moved will *always* create a new representation, unless the in is + /// empty static ComPtr create(const String& in); - /// Create from a slice + /// Create from a slice static ComPtr create(const UnownedStringSlice& slice); - /// Moves from in into the created blob. - /// NOTE! That will only use the representation from in, if it is *unique* - /// otherwise it will make a new copy. + /// Moves from in into the created blob. + /// NOTE! That will only use the representation from in, if it is *unique* + /// otherwise it will make a new copy. static ComPtr moveCreate(String& in); static ComPtr moveCreate(String&& in); - /// Dtor + /// Dtor ~StringBlob(); protected: - - /// Init with a rep when can't be owned. + /// Init with a rep when can't be owned. void _setWithCopy(StringRepresentation* rep); - /// Init with a representation that has been moved. + /// Init with a representation that has been moved. void _setWithMove(StringRepresentation* rep); - /// Create a unique copy of rep. - /// If nullptr will work (if rep is empty, will return that) + /// Create a unique copy of rep. + /// If nullptr will work (if rep is empty, will return that) static StringRepresentation* _createUniqueCopy(StringRepresentation* rep); - /// Rep can only be nullptr or have a single ref + /// Rep can only be nullptr or have a single ref void _setUniqueRep(StringRepresentation* rep); void* getObject(const Guid& guid); - UnownedTerminatedStringSlice m_slice; ///< The contents - StringRepresentation* m_uniqueRep = nullptr; ///< Holds actual bytes. Can be nullptr if it's an empty string. + UnownedTerminatedStringSlice m_slice; ///< The contents + StringRepresentation* m_uniqueRep = + nullptr; ///< Holds actual bytes. Can be nullptr if it's an empty string. }; class ListBlob : public BlobBase @@ -91,17 +93,32 @@ public: // ICastable virtual SLANG_NO_THROW void* SLANG_MCALL castAs(const SlangUUID& guid) SLANG_OVERRIDE; // ISlangBlob - SLANG_NO_THROW void const* SLANG_MCALL getBufferPointer() SLANG_OVERRIDE { return m_data.getBuffer(); } + SLANG_NO_THROW void const* SLANG_MCALL getBufferPointer() SLANG_OVERRIDE + { + return m_data.getBuffer(); + } SLANG_NO_THROW size_t SLANG_MCALL getBufferSize() SLANG_OVERRIDE { return m_data.getCount(); } - static ComPtr create(const List& data) { return ComPtr(new ListBlob(data)); } - - static ComPtr moveCreate(List& data) { return ComPtr(new ListBlob(_Move(data))); } + static ComPtr create(const List& data) + { + return ComPtr(new ListBlob(data)); + } + + static ComPtr moveCreate(List& data) + { + return ComPtr(new ListBlob(_Move(data))); + } protected: - explicit ListBlob(const List& data) : m_data(data) {} - // Move ctor - explicit ListBlob(List&& data) : m_data(data) {} + explicit ListBlob(const List& data) + : m_data(data) + { + } + // Move ctor + explicit ListBlob(List&& data) + : m_data(data) + { + } void* getObject(const Guid& guid); @@ -126,7 +143,7 @@ public: m_capacityInBytes = size; return m_data; } - /// Allocate size including a 0 byte at `size`. + /// Allocate size including a 0 byte at `size`. void* allocateTerminated(size_t size) { SLANG_ASSUME(size != std::numeric_limits::max()); @@ -146,7 +163,8 @@ public: m_sizeInBytes = 0; m_capacityInBytes = 0; } - // Reallocate so the buffer is the specified capacity/size. Contents of buffer up to size remain intact. + // Reallocate so the buffer is the specified capacity/size. Contents of buffer up to size remain + // intact. void reallocate(size_t capacity) { if (capacity != m_capacityInBytes) @@ -156,7 +174,8 @@ public: m_capacityInBytes = capacity; } } - /// Makes this no longer own the allocation. Returns the allocated data (or nullptr if no allocation) + /// Makes this no longer own the allocation. Returns the allocated data (or nullptr if no + /// allocation) void* detach() { void* data = m_data; @@ -185,14 +204,14 @@ public: return dst; } - /// Get the allocated data. Returns nullptr if there is no allocated data + /// Get the allocated data. Returns nullptr if there is no allocated data void* getData() const { return m_data; } - /// Get the size of the allocated data. + /// Get the size of the allocated data. size_t getSizeInBytes() const { return m_sizeInBytes; } - /// Get the capacity in bytes + /// Get the capacity in bytes size_t getCapacityInBytes() const { return m_capacityInBytes; } - void setSizeInBytes(size_t size) + void setSizeInBytes(size_t size) { SLANG_ASSERT(size <= m_capacityInBytes); m_sizeInBytes = size; @@ -205,13 +224,14 @@ public: Swap(m_capacityInBytes, rhs.m_capacityInBytes); } - /// True if has zero termination, at the byte at m_sizeInBytes - bool isTerminated() const { return m_capacityInBytes > m_sizeInBytes && ((const char*)m_data)[m_sizeInBytes] == 0; } + /// True if has zero termination, at the byte at m_sizeInBytes + bool isTerminated() const + { + return m_capacityInBytes > m_sizeInBytes && ((const char*)m_data)[m_sizeInBytes] == 0; + } - ScopedAllocation() : - m_data(nullptr), - m_sizeInBytes(0), - m_capacityInBytes(0) + ScopedAllocation() + : m_data(nullptr), m_sizeInBytes(0), m_capacityInBytes(0) { } @@ -228,15 +248,21 @@ private: }; /** A blob that manages some raw data that it owns. -*/ + */ class RawBlob : public BlobBase { public: // ICastable virtual SLANG_NO_THROW void* SLANG_MCALL castAs(const SlangUUID& guid) SLANG_OVERRIDE; // ISlangBlob - SLANG_NO_THROW void const* SLANG_MCALL getBufferPointer() SLANG_OVERRIDE { return m_data.getData(); } - SLANG_NO_THROW size_t SLANG_MCALL getBufferSize() SLANG_OVERRIDE { return m_data.getSizeInBytes(); } + SLANG_NO_THROW void const* SLANG_MCALL getBufferPointer() SLANG_OVERRIDE + { + return m_data.getData(); + } + SLANG_NO_THROW size_t SLANG_MCALL getBufferSize() SLANG_OVERRIDE + { + return m_data.getSizeInBytes(); + } static ComPtr moveCreate(ScopedAllocation& alloc) { @@ -245,7 +271,7 @@ public: return ComPtr(blob); } - /// Create a blob that will retain (a copy of) raw data. + /// Create a blob that will retain (a copy of) raw data. static inline ComPtr create(void const* inData, size_t size) { return ComPtr(new RawBlob(inData, size)); @@ -254,10 +280,7 @@ public: protected: // Ctor // NOTE! Takes a copy of the input data - RawBlob(const void* data, size_t size) - { - memcpy(m_data.allocateTerminated(size), data, size); - } + RawBlob(const void* data, size_t size) { memcpy(m_data.allocateTerminated(size), data, size); } void* getObject(const Guid& guid); @@ -281,9 +304,8 @@ public: protected: // Ctor - UnownedRawBlob(const void* data, size_t size) : - m_data(data), - m_dataSizeInBytes(size) + UnownedRawBlob(const void* data, size_t size) + : m_data(data), m_dataSizeInBytes(size) { } @@ -300,9 +322,9 @@ This is useful when a Blob is useful to represent some global immutable chunk of class StaticBlob : public ISlangBlob, public ICastable { public: - // ISlangUnknown - SLANG_NO_THROW SlangResult SLANG_MCALL queryInterface(SlangUUID const& uuid, void** outObject) SLANG_OVERRIDE; + SLANG_NO_THROW SlangResult SLANG_MCALL queryInterface(SlangUUID const& uuid, void** outObject) + SLANG_OVERRIDE; SLANG_NO_THROW uint32_t SLANG_MCALL addRef() SLANG_OVERRIDE { return 1; } SLANG_NO_THROW uint32_t SLANG_MCALL release() SLANG_OVERRIDE { return 1; } @@ -313,9 +335,8 @@ public: SLANG_NO_THROW void const* SLANG_MCALL getBufferPointer() SLANG_OVERRIDE { return m_data; } SLANG_NO_THROW size_t SLANG_MCALL getBufferSize() SLANG_OVERRIDE { return m_dataCount; } - StaticBlob(const void* data, size_t dataCount): - m_data(data), - m_dataCount(dataCount) + StaticBlob(const void* data, size_t dataCount) + : m_data(data), m_dataCount(dataCount) { } @@ -334,8 +355,14 @@ public: virtual SLANG_NO_THROW void* SLANG_MCALL castAs(const SlangUUID& guid) SLANG_OVERRIDE; // ISlangBlob - SLANG_NO_THROW void const* SLANG_MCALL getBufferPointer() SLANG_OVERRIDE { return m_blob->getBufferPointer(); } - SLANG_NO_THROW size_t SLANG_MCALL getBufferSize() SLANG_OVERRIDE { return m_blob->getBufferSize(); } + SLANG_NO_THROW void const* SLANG_MCALL getBufferPointer() SLANG_OVERRIDE + { + return m_blob->getBufferPointer(); + } + SLANG_NO_THROW size_t SLANG_MCALL getBufferSize() SLANG_OVERRIDE + { + return m_blob->getBufferSize(); + } static inline ComPtr create(ISlangBlob* blob, ISlangUnknown* scope) { @@ -343,11 +370,9 @@ public: } protected: - // Ctor - ScopeBlob(ISlangBlob* blob, ISlangUnknown* scope) : - m_blob(blob), - m_scope(scope) + ScopeBlob(ISlangBlob* blob, ISlangUnknown* scope) + : m_blob(blob), m_scope(scope) { // Cache the ICastable interface if there is one. blob->queryInterface(SLANG_IID_PPV_ARGS(m_castable.writeRef())); @@ -355,7 +380,8 @@ protected: ComPtr m_scope; ComPtr m_blob; - ComPtr m_castable; ///< Set if the blob has this interface. Set to nullptr if does not. + ComPtr + m_castable; ///< Set if the blob has this interface. Set to nullptr if does not. }; } // namespace Slang diff --git a/source/core/slang-byte-encode-util.cpp b/source/core/slang-byte-encode-util.cpp index c7022397f..acafdf2b4 100644 --- a/source/core/slang-byte-encode-util.cpp +++ b/source/core/slang-byte-encode-util.cpp @@ -1,17 +1,18 @@ #include "slang-byte-encode-util.h" -namespace Slang { +namespace Slang +{ // Descriptions of algorithms here... // https://github.com/stoklund/varint #if SLANG_LITTLE_ENDIAN && SLANG_UNALIGNED_ACCESS // Testing on i7, unaligned access is around 40% faster -# define SLANG_BYTE_ENCODE_USE_UNALIGNED_ACCESS 1 +#define SLANG_BYTE_ENCODE_USE_UNALIGNED_ACCESS 1 #endif #ifndef SLANG_BYTE_ENCODE_USE_UNALIGNED_ACCESS -# define SLANG_BYTE_ENCODE_USE_UNALIGNED_ACCESS 0 +#define SLANG_BYTE_ENCODE_USE_UNALIGNED_ACCESS 0 #endif #define SLANG_REPEAT_2(n) n, n @@ -22,23 +23,22 @@ namespace Slang { #define SLANG_REPEAT_64(n) SLANG_REPEAT_32(n), SLANG_REPEAT_32(n) #define SLANG_REPEAT_128(n) SLANG_REPEAT_64(n), SLANG_REPEAT_64(n) -/* static */const int8_t ByteEncodeUtil::s_msb8[256] = -{ - - 1, - 0, - SLANG_REPEAT_2(1), - SLANG_REPEAT_4(2), - SLANG_REPEAT_8(3), - SLANG_REPEAT_16(4), +/* static */ const int8_t ByteEncodeUtil::s_msb8[256] = { + -1, + 0, + SLANG_REPEAT_2(1), + SLANG_REPEAT_4(2), + SLANG_REPEAT_8(3), + SLANG_REPEAT_16(4), SLANG_REPEAT_32(5), SLANG_REPEAT_64(6), SLANG_REPEAT_128(7), }; -/* static */size_t ByteEncodeUtil::calcEncodeLiteSizeUInt32(const uint32_t* in, size_t num) +/* static */ size_t ByteEncodeUtil::calcEncodeLiteSizeUInt32(const uint32_t* in, size_t num) { size_t totalNumEncodeBytes = 0; - + for (size_t i = 0; i < num; i++) { const uint32_t v = in[i]; @@ -59,7 +59,10 @@ namespace Slang { return totalNumEncodeBytes; } -/* static */size_t ByteEncodeUtil::encodeLiteUInt32(const uint32_t* in, size_t num, uint8_t* encodeOut) +/* static */ size_t ByteEncodeUtil::encodeLiteUInt32( + const uint32_t* in, + size_t num, + uint8_t* encodeOut) { uint8_t* encodeStart = encodeOut; @@ -67,7 +70,7 @@ namespace Slang { { uint32_t v = in[i]; - if(v < kLiteCut1) + if (v < kLiteCut1) { *encodeOut++ = uint8_t(v); } @@ -95,7 +98,10 @@ namespace Slang { return size_t(encodeOut - encodeStart); } -/* static */void ByteEncodeUtil::encodeLiteUInt32(const uint32_t* in, size_t num, List& encodeArrayOut) +/* static */ void ByteEncodeUtil::encodeLiteUInt32( + const uint32_t* in, + size_t num, + List& encodeArrayOut) { // Make sure there is at least enough space for all bytes encodeArrayOut.setCount(num); @@ -111,7 +117,7 @@ namespace Slang { const size_t offset = size_t(encodeOut - encodeArrayOut.begin()); const UInt oldCapacity = encodeArrayOut.getCapacity(); - + // Make some more space encodeArrayOut.reserve(oldCapacity + (oldCapacity >> 1) + kMaxLiteEncodeUInt32); // Make the size the capacity @@ -154,7 +160,7 @@ namespace Slang { encodeArrayOut.compress(); } -/* static */int ByteEncodeUtil::encodeLiteUInt32(uint32_t in, uint8_t out[kMaxLiteEncodeUInt32]) +/* static */ int ByteEncodeUtil::encodeLiteUInt32(uint32_t in, uint8_t out[kMaxLiteEncodeUInt32]) { // 0-184 1 byte value = B0 // 185 - 248 2 bytes value = 185 + 256 * (B0 - 185) + B1 @@ -187,8 +193,7 @@ namespace Slang { } } -static const uint32_t s_unalignedUInt32Mask[5] = -{ +static const uint32_t s_unalignedUInt32Mask[5] = { 0x00000000, 0x000000ff, 0x0000ffff, @@ -196,8 +201,8 @@ static const uint32_t s_unalignedUInt32Mask[5] = 0xffffffff, }; -// Decode the >= kLiteCut2. -// in is pointing past the first byte. +// Decode the >= kLiteCut2. +// in is pointing past the first byte. // Only valid numBytesRemaining is 2, 3, or 4 SLANG_FORCE_INLINE static uint32_t _decodeLiteCut2UInt32(const uint8_t* in, int numBytesRemaining) { @@ -205,26 +210,26 @@ SLANG_FORCE_INLINE static uint32_t _decodeLiteCut2UInt32(const uint8_t* in, int #if SLANG_BYTE_ENCODE_USE_UNALIGNED_ACCESS switch (numBytesRemaining) { - case 2: value = *(const uint16_t*)in; break; - case 3: value = (uint32_t(in[2]) << 16) | (uint32_t(in[1]) << 8) | uint32_t(in[0]); break; - case 4: value = *(const uint32_t*)in; break; - default: break; + case 2: value = *(const uint16_t*)in; break; + case 3: value = (uint32_t(in[2]) << 16) | (uint32_t(in[1]) << 8) | uint32_t(in[0]); break; + case 4: value = *(const uint32_t*)in; break; + default: break; } #else // This works on all cpus although slower value = in[0]; switch (numBytesRemaining) { - case 4: value |= uint32_t(in[3]) << 24; /* fall thru */ - case 3: value |= uint32_t(in[2]) << 16; /* fall thru */ - case 2: value |= uint32_t(in[1]) << 8; /* fall thru */ - case 1: break; + case 4: value |= uint32_t(in[3]) << 24; /* fall thru */ + case 3: value |= uint32_t(in[2]) << 16; /* fall thru */ + case 2: value |= uint32_t(in[1]) << 8; /* fall thru */ + case 1: break; } #endif return value; } -/* static */int ByteEncodeUtil::decodeLiteUInt32(const uint8_t* in, uint32_t* out) +/* static */ int ByteEncodeUtil::decodeLiteUInt32(const uint8_t* in, uint32_t* out) { uint8_t b0 = *in++; if (b0 < kLiteCut1) @@ -246,7 +251,10 @@ SLANG_FORCE_INLINE static uint32_t _decodeLiteCut2UInt32(const uint8_t* in, int } } -/* static */size_t ByteEncodeUtil::decodeLiteUInt32(const uint8_t* encodeIn, size_t numValues, uint32_t* valuesOut) +/* static */ size_t ByteEncodeUtil::decodeLiteUInt32( + const uint8_t* encodeIn, + size_t numValues, + uint32_t* valuesOut) { const uint8_t* encodeStart = encodeIn; @@ -267,13 +275,13 @@ SLANG_FORCE_INLINE static uint32_t _decodeLiteCut2UInt32(const uint8_t* in, int const int numBytesRemaining = b0 - kLiteCut2 + 2 - 1; // For unaligned access, do not use unaligned access for the last two values, - // (3rd last is safe because this value will have at least 2 bytes, followed by at worst two 1-byte values) - // otherwise we can access outside the bounds of the encoded array + // (3rd last is safe because this value will have at least 2 bytes, followed by at worst + // two 1-byte values) otherwise we can access outside the bounds of the encoded array // This prevents memory validation tools from causing an exception here if (SLANG_BYTE_ENCODE_USE_UNALIGNED_ACCESS && i < numValues - 2) { const uint32_t mask = s_unalignedUInt32Mask[numBytesRemaining]; - //const uint32_t mask = ~(uint32_t(0xffffff00) << ((numBytesRemaining - 1) * 8)); + // const uint32_t mask = ~(uint32_t(0xffffff00) << ((numBytesRemaining - 1) * 8)); valuesOut[i] = (*(const uint32_t*)encodeIn) & mask; } else diff --git a/source/core/slang-byte-encode-util.h b/source/core/slang-byte-encode-util.h index 728f9ac2f..81fc0ef98 100644 --- a/source/core/slang-byte-encode-util.h +++ b/source/core/slang-byte-encode-util.h @@ -3,88 +3,90 @@ #include "slang-list.h" -namespace Slang { +namespace Slang +{ struct ByteEncodeUtil { enum { kMaxLiteEncodeUInt16 = 3, /// One byte for prefix, the remaining 2 bytes hold the value - kMaxLiteEncodeUInt32 = 5, /// One byte for prefix, the remaining 4 bytes hold the value + kMaxLiteEncodeUInt32 = 5, /// One byte for prefix, the remaining 4 bytes hold the value // Cut values for 'Lite' encoding style kLiteCut1 = 185, kLiteCut2 = 249, }; - /** Find the most significant bit for 8 bits - @param v The value to find most significant bit on - @return The most significant bit, or -1 if no bits are set - */ + /** Find the most significant bit for 8 bits + @param v The value to find most significant bit on + @return The most significant bit, or -1 if no bits are set + */ SLANG_FORCE_INLINE static int calcMsb8(uint32_t v); - - /** Find the most significant bit for 32 bits - @param v The value to find most significant bit on - @return The most significant bit, or -1 if no bits are set - */ + + /** Find the most significant bit for 32 bits + @param v The value to find most significant bit on + @return The most significant bit, or -1 if no bits are set + */ SLANG_FORCE_INLINE static int calcMsb32(uint32_t v); - - /** Calculates the 'most significant' byte ie the highest bytes that is non zero. - Note return value is *undefined* if in is 0. - @param in Value - cannot be 0. - @return The byte index of the highest byte that is non zero. - */ + + /** Calculates the 'most significant' byte ie the highest bytes that is non zero. + Note return value is *undefined* if in is 0. + @param in Value - cannot be 0. + @return The byte index of the highest byte that is non zero. + */ SLANG_FORCE_INLINE static int calcNonZeroMsByte32(uint32_t in); - /** Calculates the 'most significant' byte ie the highest bytes that is non zero. - @param in Value - cannot be 0. - @return The byte index of the highest byte that is non zero. - */ + /** Calculates the 'most significant' byte ie the highest bytes that is non zero. + @param in Value - cannot be 0. + @return The byte index of the highest byte that is non zero. + */ SLANG_FORCE_INLINE static int calcMsByte32(uint32_t in); - /// Calculate the size of encoding bytes + /// Calculate the size of encoding bytes static size_t calcEncodeLiteSizeUInt32(const uint32_t* in, size_t num); - /// Calculate the size of a single value + /// Calculate the size of a single value static size_t calcEncodeLiteSizeUInt32(uint32_t in); - - /** Encodes a uint32_t as an integer - @return the number of bytes needed to encode */ + + /** Encodes a uint32_t as an integer + @return the number of bytes needed to encode */ static int encodeLiteUInt32(uint32_t in, uint8_t out[kMaxLiteEncodeUInt32]); - /** Decode a lite encoding. - @param in The lite encoded bytes - @param out Value constructed - @return number of bytes on in consumed */ + /** Decode a lite encoding. + @param in The lite encoded bytes + @param out Value constructed + @return number of bytes on in consumed */ static int decodeLiteUInt32(const uint8_t* in, uint32_t* out); - /** Encode an array of uint32_t - @param in The values to encode - @param num The amount of values to encode - @param encodeOut The buffer to hold the encoded value. MUST be large enough to hold the encoding - @return The size of the encoding in bytes - */ + /** Encode an array of uint32_t + @param in The values to encode + @param num The amount of values to encode + @param encodeOut The buffer to hold the encoded value. MUST be large enough to hold the encoding + @return The size of the encoding in bytes + */ static size_t encodeLiteUInt32(const uint32_t* in, size_t num, uint8_t* encodeOut); - /** Encode an array of uint32_t - @param in The values to encode - @param num The amount of values to encode - @param encodeOut The buffer to hold the encoded value. - */ + /** Encode an array of uint32_t + @param in The values to encode + @param num The amount of values to encode + @param encodeOut The buffer to hold the encoded value. + */ static void encodeLiteUInt32(const uint32_t* in, size_t num, List& encodeOut); - /** Encode an array of uint32_t - @param encodeIn The encoded values - @param numValues The amount of values to be decoded (NOTE! This is the number of valuesOut, not encodeIn) - @param valuesOut The buffer to hold the encoded value. MUST be large enough to hold the encoding - @return The amount of bytes decoded - */ - static size_t decodeLiteUInt32(const uint8_t* encodeIn, size_t numValues, uint32_t* valuesOut); + /** Encode an array of uint32_t + @param encodeIn The encoded values + @param numValues The amount of values to be decoded (NOTE! This is the number of valuesOut, not + encodeIn) + @param valuesOut The buffer to hold the encoded value. MUST be large enough to hold the encoding + @return The amount of bytes decoded + */ + static size_t decodeLiteUInt32(const uint8_t* encodeIn, size_t numValues, uint32_t* valuesOut); - /// Table that maps 8 bits to it's most significant bit. If 0 returns -1. + /// Table that maps 8 bits to it's most significant bit. If 0 returns -1. static const int8_t s_msb8[256]; }; -#if SLANG_VC +#if SLANG_VC // Works on ARM and x86/64 on visual studio compiler // --------------------------------------------------------------------------- @@ -102,7 +104,7 @@ SLANG_FORCE_INLINE int ByteEncodeUtil::calcNonZeroMsByte32(uint32_t in) SLANG_FORCE_INLINE int ByteEncodeUtil::calcMsByte32(uint32_t in) { if (in == 0) - { + { return -1; } // Can use intrinsic @@ -113,7 +115,7 @@ SLANG_FORCE_INLINE int ByteEncodeUtil::calcMsByte32(uint32_t in) } // --------------------------------------------------------------------------- -SLANG_FORCE_INLINE /* static */int ByteEncodeUtil::calcMsb8(uint32_t v) +SLANG_FORCE_INLINE /* static */ int ByteEncodeUtil::calcMsb8(uint32_t v) { SLANG_ASSERT((v & 0xffffff00) == 0); if (v == 0) @@ -126,7 +128,7 @@ SLANG_FORCE_INLINE /* static */int ByteEncodeUtil::calcMsb8(uint32_t v) } // --------------------------------------------------------------------------- -SLANG_FORCE_INLINE /* static */int ByteEncodeUtil::calcMsb32(uint32_t v) +SLANG_FORCE_INLINE /* static */ int ByteEncodeUtil::calcMsb32(uint32_t v) { if (v == 0) { @@ -140,41 +142,36 @@ SLANG_FORCE_INLINE /* static */int ByteEncodeUtil::calcMsb32(uint32_t v) #else // --------------------------------------------------------------------------- -SLANG_FORCE_INLINE /* static */int ByteEncodeUtil::calcNonZeroMsByte32(uint32_t in) +SLANG_FORCE_INLINE /* static */ int ByteEncodeUtil::calcNonZeroMsByte32(uint32_t in) { - return (in & 0xffff0000) ? - ((in & 0xff000000) ? 3 : 2) : - ((in & 0x0000ff00) ? 1 : 0); + return (in & 0xffff0000) ? ((in & 0xff000000) ? 3 : 2) : ((in & 0x0000ff00) ? 1 : 0); } // --------------------------------------------------------------------------- -SLANG_FORCE_INLINE /* static */int ByteEncodeUtil::calcMsByte32(uint32_t in) +SLANG_FORCE_INLINE /* static */ int ByteEncodeUtil::calcMsByte32(uint32_t in) { - return (in & 0xffff0000) ? - ((in & 0xff000000) ? 3 : 2) : - ((in & 0x0000ff00) ? 1 : - ((in == 0) ? -1 : 0)); + return (in & 0xffff0000) ? ((in & 0xff000000) ? 3 : 2) + : ((in & 0x0000ff00) ? 1 : ((in == 0) ? -1 : 0)); } // --------------------------------------------------------------------------- -SLANG_FORCE_INLINE /* static */int ByteEncodeUtil::calcMsb8(uint32_t v) -{ - SLANG_ASSERT((v & 0xffffff00) == 0); - return s_msb8[v]; +SLANG_FORCE_INLINE /* static */ int ByteEncodeUtil::calcMsb8(uint32_t v) +{ + SLANG_ASSERT((v & 0xffffff00) == 0); + return s_msb8[v]; } // --------------------------------------------------------------------------- -SLANG_FORCE_INLINE /* static */int ByteEncodeUtil::calcMsb32(uint32_t v) +SLANG_FORCE_INLINE /* static */ int ByteEncodeUtil::calcMsb32(uint32_t v) { - return (v & 0xffff0000) ? - ((v & 0xff000000) ? s_msb8[v >> 24] + 24 : s_msb8[v >> 16] + 16) : - ((v & 0x0000ff00) ? s_msb8[v >> 8] + 8 : s_msb8[v]); + return (v & 0xffff0000) ? ((v & 0xff000000) ? s_msb8[v >> 24] + 24 : s_msb8[v >> 16] + 16) + : ((v & 0x0000ff00) ? s_msb8[v >> 8] + 8 : s_msb8[v]); } #endif // --------------------------------------------------------------------------- -inline /* static */size_t ByteEncodeUtil::calcEncodeLiteSizeUInt32(uint32_t v) +inline /* static */ size_t ByteEncodeUtil::calcEncodeLiteSizeUInt32(uint32_t v) { if (v < kLiteCut1) { diff --git a/source/core/slang-castable.cpp b/source/core/slang-castable.cpp index f3c6541dd..ece87fe2b 100644 --- a/source/core/slang-castable.cpp +++ b/source/core/slang-castable.cpp @@ -1,11 +1,12 @@ // slang-castable.cpp #include "slang-castable.h" -namespace Slang { +namespace Slang +{ /* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! CastableUtil !!!!!!!!!!!!!!!!!!!!!!!!!!! */ -/* static */ComPtr CastableUtil::getCastable(ISlangUnknown* unk) +/* static */ ComPtr CastableUtil::getCastable(ISlangUnknown* unk) { SLANG_ASSERT(unk); ComPtr castable; @@ -52,8 +53,7 @@ void* UnknownCastableAdapter::castAs(const Guid& guid) void* UnknownCastableAdapter::getInterface(const Guid& guid) { - if (guid == ISlangUnknown::getTypeGuid() || - guid == ICastable::getTypeGuid() || + if (guid == ISlangUnknown::getTypeGuid() || guid == ICastable::getTypeGuid() || guid == IUnknownCastableAdapter::getTypeGuid()) { return static_cast(this); diff --git a/source/core/slang-castable.h b/source/core/slang-castable.h index e2b9c4a8e..50b41766a 100644 --- a/source/core/slang-castable.h +++ b/source/core/slang-castable.h @@ -3,16 +3,15 @@ #define SLANG_CASTABLE_H +#include "../core/slang-com-object.h" #include "slang-com-helper.h" #include "slang-com-ptr.h" -#include "../core/slang-com-object.h" - namespace Slang { // Dynamic cast of ICastable derived types -template +template SLANG_FORCE_INLINE T* dynamicCast(ICastable* castable) { if (castable) @@ -24,7 +23,7 @@ SLANG_FORCE_INLINE T* dynamicCast(ICastable* castable) } // as style cast -template +template SLANG_FORCE_INLINE T* as(ICastable* castable) { if (castable) @@ -36,34 +35,38 @@ SLANG_FORCE_INLINE T* as(ICastable* castable) } /* An interface for boxing values */ -class IBoxValueBase: public ICastable +class IBoxValueBase : public ICastable { - SLANG_COM_INTERFACE(0x8b4aad81, 0x4934, 0x4a67, { 0xb2, 0xe2, 0xe9, 0x17, 0xfc, 0x29, 0x12, 0x54 }); + SLANG_COM_INTERFACE( + 0x8b4aad81, + 0x4934, + 0x4a67, + {0xb2, 0xe2, 0xe9, 0x17, 0xfc, 0x29, 0x12, 0x54}); - /// Get the contained object + /// Get the contained object virtual SLANG_NO_THROW void* SLANG_MCALL getValuePtr() = 0; - /// Get the guid that represents the contained ref object + /// Get the guid that represents the contained ref object virtual SLANG_NO_THROW SlangUUID SLANG_MCALL getValueTypeGuid() = 0; }; -template +template class IBoxValue : public IBoxValueBase { - public: - +public: SLANG_FORCE_INLINE T& get() { return *reinterpret_cast(getValuePtr()); } SLANG_FORCE_INLINE T* getPtr() { return reinterpret_cast(getValuePtr()); } }; // Cast into a boxed value type -template +template SLANG_FORCE_INLINE IBoxValue* asBoxValue(ICastable* castable) { IBoxValueBase* base = as(castable); - return (base && base->getValueTypeGuid() == T::getTypeGuid()) ? static_cast*>(base) : nullptr; + return (base && base->getValueTypeGuid() == T::getTypeGuid()) ? static_cast*>(base) + : nullptr; } -template +template class BoxValue : public ComBaseObject, public IBoxValue { public: @@ -78,24 +81,23 @@ public: BoxValue() {} - explicit BoxValue(const T& rhs): - m_value(rhs) + explicit BoxValue(const T& rhs) + : m_value(rhs) { } protected: - void* getInterface(const Guid& guid); + void* getInterface(const Guid& guid); void* getObject(const Guid& guid); - + T m_value; }; // ------------------------------------------------------------ -template +template void* BoxValue::getInterface(const Guid& guid) { - if (guid == ISlangUnknown::getTypeGuid() || - guid == ICastable::getTypeGuid() || + if (guid == ISlangUnknown::getTypeGuid() || guid == ICastable::getTypeGuid() || guid == IBoxValueBase::getTypeGuid()) { return static_cast(this); @@ -104,7 +106,7 @@ void* BoxValue::getInterface(const Guid& guid) } // ------------------------------------------------------------ -template +template void* BoxValue::getObject(const Guid& guid) { if (guid == T::getTypeGuid()) @@ -115,7 +117,7 @@ void* BoxValue::getObject(const Guid& guid) } // ------------------------------------------------------------ -template +template void* BoxValue::castAs(const Guid& guid) { if (auto ptr = getObject(guid)) @@ -124,22 +126,28 @@ void* BoxValue::castAs(const Guid& guid) } return getInterface(guid); } - + /* Adapter interface to make a non castable types work as ICastable */ class IUnknownCastableAdapter : public ICastable { - SLANG_COM_INTERFACE(0x8b4aad81, 0x4934, 0x4a67, { 0xb2, 0xe2, 0xe9, 0x17, 0xfc, 0x29, 0x12, 0x54 }); + SLANG_COM_INTERFACE( + 0x8b4aad81, + 0x4934, + 0x4a67, + {0xb2, 0xe2, 0xe9, 0x17, 0xfc, 0x29, 0x12, 0x54}); /// When using the adapter, this provides a way to directly get the internal no ICastable type virtual SLANG_NO_THROW ISlangUnknown* SLANG_MCALL getContained() = 0; }; -/* An adapter such that types which aren't derived from ICastable, can be used as such. +/* An adapter such that types which aren't derived from ICastable, can be used as such. With the following caveats. -* the interfaces/objects of the adapter are checked *first*, so IUnknown will always be for the adapter -* assumes when doing a queryInterface on the contained item, it will remain in scope when released (this is *not* strict COM) +* the interfaces/objects of the adapter are checked *first*, so IUnknown will always be for the +adapter +* assumes when doing a queryInterface on the contained item, it will remain in scope when released +(this is *not* strict COM) */ class UnknownCastableAdapter : public ComBaseObject, public IUnknownCastableAdapter { @@ -150,10 +158,13 @@ public: SLANG_NO_THROW void* SLANG_MCALL castAs(const Guid& guid) SLANG_OVERRIDE; // IUnknownCastableAdapter - virtual SLANG_NO_THROW ISlangUnknown* SLANG_MCALL getContained() SLANG_OVERRIDE { return m_contained; } + virtual SLANG_NO_THROW ISlangUnknown* SLANG_MCALL getContained() SLANG_OVERRIDE + { + return m_contained; + } - UnknownCastableAdapter(ISlangUnknown* unk): - m_contained(unk) + UnknownCastableAdapter(ISlangUnknown* unk) + : m_contained(unk) { SLANG_ASSERT(unk); } @@ -171,15 +182,15 @@ protected: struct CastableUtil { - /// Given an ISlangUnkown return as a castable interface. - /// Can use UnknownCastableAdapter if can't queryInterface unk to ICastable + /// Given an ISlangUnkown return as a castable interface. + /// Can use UnknownCastableAdapter if can't queryInterface unk to ICastable static ComPtr getCastable(ISlangUnknown* unk); }; -// A way to clone an interface (that derives from IClonable) such that it returns an interface +// A way to clone an interface (that derives from IClonable) such that it returns an interface // of the same type. -template +template SLANG_FORCE_INLINE ComPtr cloneInterface(T* in) { SLANG_ASSERT(in); diff --git a/source/core/slang-char-encode.cpp b/source/core/slang-char-encode.cpp index 526c6c923..a27e7ba82 100644 --- a/source/core/slang-char-encode.cpp +++ b/source/core/slang-char-encode.cpp @@ -3,20 +3,23 @@ namespace Slang { -class Utf8CharEncoding : public CharEncoding +class Utf8CharEncoding : public CharEncoding { public: typedef CharEncoding Super; - virtual void encode(const UnownedStringSlice& slice, List& ioBuffer) override - { + virtual void encode(const UnownedStringSlice& slice, List& ioBuffer) override + { ioBuffer.addRange((const Byte*)slice.begin(), slice.getLength()); - } - virtual void decode(const Byte* bytes, int length, List& ioChars) override - { + } + virtual void decode(const Byte* bytes, int length, List& ioChars) override + { ioChars.addRange((const char*)bytes, length); - } - Utf8CharEncoding() : Super(CharEncodeType::UTF8) {} + } + Utf8CharEncoding() + : Super(CharEncodeType::UTF8) + { + } }; class Utf32CharEncoding : public CharEncoding @@ -24,93 +27,98 @@ class Utf32CharEncoding : public CharEncoding public: typedef CharEncoding Super; - virtual void encode(const UnownedStringSlice& slice, List& ioBuffer) override - { - Index ptr = 0; - while (ptr < slice.getLength()) - { - const Char32 codePoint = getUnicodePointFromUTF8([&]() -> Byte - { - if (ptr < slice.getLength()) - return slice[ptr++]; - else - return '\0'; - }); + virtual void encode(const UnownedStringSlice& slice, List& ioBuffer) override + { + Index ptr = 0; + while (ptr < slice.getLength()) + { + const Char32 codePoint = getUnicodePointFromUTF8( + [&]() -> Byte + { + if (ptr < slice.getLength()) + return slice[ptr++]; + else + return '\0'; + }); // Note: Assumes byte order is same as arch byte order ioBuffer.addRange((const Byte*)&codePoint, 4); - } - } - virtual void decode(const Byte* bytes, int length, List& ioBuffer) override - { + } + } + virtual void decode(const Byte* bytes, int length, List& ioBuffer) override + { // Note: Assumes bytes is Char32 aligned SLANG_ASSERT((size_t(bytes) & 3) == 0); - const Char32* content = (const Char32*)bytes; - for (int i = 0; i < (length >> 2); i++) - { - char buf[5]; - int count = encodeUnicodePointToUTF8(content[i], buf); + const Char32* content = (const Char32*)bytes; + for (int i = 0; i < (length >> 2); i++) + { + char buf[5]; + int count = encodeUnicodePointToUTF8(content[i], buf); for (int j = 0; j < count; j++) ioBuffer.addRange(buf, count); - } - } + } + } - Utf32CharEncoding() : Super(CharEncodeType::UTF32) {} + Utf32CharEncoding() + : Super(CharEncodeType::UTF32) + { + } }; -class Utf16CharEncoding : public CharEncoding //UTF16 +class Utf16CharEncoding : public CharEncoding // UTF16 { public: typedef CharEncoding Super; - Utf16CharEncoding(bool reverseOrder): - Super(reverseOrder ? CharEncodeType::UTF16Reversed : CharEncodeType::UTF16), - m_reverseOrder(reverseOrder) - {} - virtual void encode(const UnownedStringSlice& slice, List& ioBuffer) override - { - Index index = 0; - while (index < slice.getLength()) - { - const Char32 codePoint = getUnicodePointFromUTF8([&]() -> Byte - { - if (index < slice.getLength()) - return slice[index++]; - else - return '\0'; - }); - - Char16 buffer[2]; - int count; - if (!m_reverseOrder) - count = encodeUnicodePointToUTF16(codePoint, buffer); - else - count = encodeUnicodePointToUTF16Reversed(codePoint, buffer); + Utf16CharEncoding(bool reverseOrder) + : Super(reverseOrder ? CharEncodeType::UTF16Reversed : CharEncodeType::UTF16) + , m_reverseOrder(reverseOrder) + { + } + virtual void encode(const UnownedStringSlice& slice, List& ioBuffer) override + { + Index index = 0; + while (index < slice.getLength()) + { + const Char32 codePoint = getUnicodePointFromUTF8( + [&]() -> Byte + { + if (index < slice.getLength()) + return slice[index++]; + else + return '\0'; + }); + + Char16 buffer[2]; + int count; + if (!m_reverseOrder) + count = encodeUnicodePointToUTF16(codePoint, buffer); + else + count = encodeUnicodePointToUTF16Reversed(codePoint, buffer); ioBuffer.addRange((const Byte*)buffer, count * 2); - } - } - virtual void decode(const Byte* bytes, int length, List& ioBuffer) override - { - Index index = 0; - while (index < length) - { - auto readByte = [&]() -> Byte - { - return (index < length) ? bytes[index++] : Byte(0); - }; - const Char32 codePoint = m_reverseOrder ? - getUnicodePointFromUTF16Reversed(readByte) : - getUnicodePointFromUTF16(readByte); - - char buf[5]; - int count = encodeUnicodePointToUTF8(codePoint, buf); - ioBuffer.addRange((const char*)buf, count); - } - } + } + } + virtual void decode(const Byte* bytes, int length, List& ioBuffer) override + { + Index index = 0; + while (index < length) + { + auto readByte = [&]() -> Byte { return (index < length) ? bytes[index++] : Byte(0); }; + const Char32 codePoint = m_reverseOrder ? getUnicodePointFromUTF16Reversed(readByte) + : getUnicodePointFromUTF16(readByte); + + char buf[5]; + int count = encodeUnicodePointToUTF8(codePoint, buf); + ioBuffer.addRange((const char*)buf, count); + } + } private: bool m_reverseOrder = false; }; -/* static */CharEncodeType CharEncoding::determineEncoding(const Byte* bytes, size_t bytesCount, size_t& outOffset) +/* static */ CharEncodeType CharEncoding::determineEncoding( + const Byte* bytes, + size_t bytesCount, + size_t& outOffset) { // TODO(JS): Assumes the bytes are suitably aligned @@ -137,7 +145,7 @@ private: // If we don't have a 'mark' byte then we are bit stumped. We'll look for // null (non-terminator) bytes and assume they mean we have a 16-bit encoding - for(size_t i = 0; i < (bytesCount-1); i += 2) + for (size_t i = 0; i < (bytesCount - 1); i += 2) { #if SLANG_LITTLE_ENDIAN const auto low = bytes[i]; @@ -164,41 +172,42 @@ static Utf16CharEncoding _utf16Encoding(false); static Utf16CharEncoding _utf16EncodingReversed(true); static Utf32CharEncoding _utf32Encoding; -/* static */CharEncoding* const CharEncoding::g_encoding[Index(CharEncodeType::CountOf)] -{ - &_utf8Encoding, // UTF8, - &_utf16Encoding, // UTF16, - &_utf16EncodingReversed, // UTF16Reversed, - &_utf32Encoding, // UTF32, +/* static */ CharEncoding* const CharEncoding::g_encoding[Index(CharEncodeType::CountOf)]{ + &_utf8Encoding, // UTF8, + &_utf16Encoding, // UTF16, + &_utf16EncodingReversed, // UTF16Reversed, + &_utf32Encoding, // UTF32, }; CharEncoding* CharEncoding::UTF8 = &_utf8Encoding; CharEncoding* CharEncoding::UTF16 = &_utf16Encoding; CharEncoding* CharEncoding::UTF16Reversed = &_utf16EncodingReversed; CharEncoding* CharEncoding::UTF32 = &_utf32Encoding; - + /* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! UTF8Util !!!!!!!!!!!!!!!!!!!!!!!!! */ -/* static */Index UTF8Util::calcCodePointCount(const UnownedStringSlice& in) +/* static */ Index UTF8Util::calcCodePointCount(const UnownedStringSlice& in) { Index count = 0; // Analyse with bytes... const int8_t* cur = (const int8_t*)in.begin(); - const int8_t*const end = (const int8_t*)in.end(); + const int8_t* const end = (const int8_t*)in.end(); while (cur < end) { const auto c = *cur++; - + count++; // If c < 0 it means the top bit is set... which means we have multiple bytes if (c < 0) { // https://en.wikipedia.org/wiki/UTF-8 - // All continuation bytes contain exactly six bits from the code point.So the next six bits of the code point - /// are stored in the low order six bits of the next byte, and 10 is stored in the high order two bits to + // All continuation bytes contain exactly six bits from the code point.So the next six + // bits of the code point + /// are stored in the low order six bits of the next byte, and 10 is stored in the high + /// order two bits to // mark it as a continuation byte(so 10000010). while (cur < end && (*cur & 0xc0) == 0x80) @@ -217,7 +226,8 @@ Index UTF8Util::calcUTF16CharCount(const UnownedStringSlice& in) Index readPtr = 0; for (;;) { - int c = getUnicodePointFromUTF8([&]() -> Byte + int c = getUnicodePointFromUTF8( + [&]() -> Byte { if (readPtr < in.getLength()) return in[readPtr++]; diff --git a/source/core/slang-char-encode.h b/source/core/slang-char-encode.h index a7cd501ab..74968a6ab 100644 --- a/source/core/slang-char-encode.h +++ b/source/core/slang-char-encode.h @@ -1,13 +1,13 @@ #ifndef SLANG_CORE_CHAR_ENCODE_H #define SLANG_CORE_CHAR_ENCODE_H -#include "slang-secure-crt.h" #include "slang-basic.h" +#include "slang-secure-crt.h" namespace Slang { -// NOTE! Order must be kept the same to match up with +// NOTE! Order must be kept the same to match up with enum class CharEncodeType { UTF8, @@ -17,7 +17,7 @@ enum class CharEncodeType CountOf, }; -template +template Char32 getUnicodePointFromUTF8(const ReadByteFunc& readByte) { Char32 codePoint = 0; @@ -38,7 +38,7 @@ Char32 getUnicodePointFromUTF8(const ReadByteFunc& readByte) return codePoint; } -template +template Char32 getUnicodePointFromUTF16(const ReadByteFunc& readByte) { uint32_t byte0 = Byte(readByte()); @@ -55,7 +55,7 @@ Char32 getUnicodePointFromUTF16(const ReadByteFunc& readByte) return Char32(word0); } -template +template Char32 getUnicodePointFromUTF16Reversed(const ReadByteFunc& readByte) { uint32_t byte0 = Byte(readByte()); @@ -72,7 +72,7 @@ Char32 getUnicodePointFromUTF16Reversed(const ReadByteFunc& readByte) return Char32(word0); } -template +template Char32 getUnicodePointFromUTF32(const ReadByteFunc& readByte) { uint32_t byte0 = Byte(readByte()); @@ -163,52 +163,55 @@ static const Char16 kUTF16ReversedHeader = 0xFFFE; class CharEncoding { public: - static CharEncoding* UTF8,* UTF16,* UTF16Reversed,* UTF32; + static CharEncoding *UTF8, *UTF16, *UTF16Reversed, *UTF32; - /// Encode Utf8 held in slice append into ioBuffer + /// Encode Utf8 held in slice append into ioBuffer virtual void encode(const UnownedStringSlice& str, List& ioBuffer) = 0; - /// Decode buffer into Utf8 held in ioBuffer + /// Decode buffer into Utf8 held in ioBuffer virtual void decode(const Byte* buffer, int length, List& ioBuffer) = 0; - virtual ~CharEncoding() {} + virtual ~CharEncoding() {} - /// Get the encoding type + /// Get the encoding type CharEncodeType getEncodingType() const { return m_encodingType; } - /// Given some bytes determines a character encoding type, based on the initial bytes. - /// If can't be determined will assume UTF8. - /// Outputs the offset to the first non mark in outOffset - static CharEncodeType determineEncoding(const Byte* bytes, size_t bytesCount, size_t& outOffset); + /// Given some bytes determines a character encoding type, based on the initial bytes. + /// If can't be determined will assume UTF8. + /// Outputs the offset to the first non mark in outOffset + static CharEncodeType determineEncoding( + const Byte* bytes, + size_t bytesCount, + size_t& outOffset); - /// Get the + /// Get the static CharEncoding* getEncoding(CharEncodeType type) { return g_encoding[Index(type)]; } - CharEncoding(CharEncodeType encodingType) : - m_encodingType(encodingType) + CharEncoding(CharEncodeType encodingType) + : m_encodingType(encodingType) { } protected: - CharEncodeType m_encodingType; - static CharEncoding*const g_encoding[Index(CharEncodeType::CountOf)]; + static CharEncoding* const g_encoding[Index(CharEncodeType::CountOf)]; }; struct UTF8Util { - /// Given a slice calculate the number of code points (unicode chars) - /// - /// NOTE! This doesn't check the *validity* of code points/encoding. - /// Non valid utf8 input or ending starting in partial characters, will produce - /// undefined results without error. + /// Given a slice calculate the number of code points (unicode chars) + /// + /// NOTE! This doesn't check the *validity* of code points/encoding. + /// Non valid utf8 input or ending starting in partial characters, will produce + /// undefined results without error. static Index calcCodePointCount(const UnownedStringSlice& in); - /// Given a slice in UTF8, calculate the number of UTF16 characters needed to represent the string. + /// Given a slice in UTF8, calculate the number of UTF16 characters needed to represent the + /// string. static Index calcUTF16CharCount(const UnownedStringSlice& in); }; -} +} // namespace Slang #endif diff --git a/source/core/slang-char-util.cpp b/source/core/slang-char-util.cpp index ea9e6dbf2..f9c61ec03 100644 --- a/source/core/slang-char-util.cpp +++ b/source/core/slang-char-util.cpp @@ -1,8 +1,9 @@ #include "slang-char-util.h" -namespace Slang { +namespace Slang +{ -/* static */CharUtil::CharFlagMap CharUtil::makeCharFlagMap() +/* static */ CharUtil::CharFlagMap CharUtil::makeCharFlagMap() { CharUtil::CharFlagMap map; memset(&map, 0, sizeof(map)); @@ -46,11 +47,11 @@ namespace Slang { return map; } -/* static */int CharUtil::_ensureLink() +/* static */ int CharUtil::_ensureLink() { return makeCharFlagMap().flags[0]; } -/* static */const CharUtil::CharFlagMap CharUtil::g_charFlagMap = makeCharFlagMap(); +/* static */ const CharUtil::CharFlagMap CharUtil::g_charFlagMap = makeCharFlagMap(); } // namespace Slang diff --git a/source/core/slang-char-util.h b/source/core/slang-char-util.h index 88af24426..896eb6956 100644 --- a/source/core/slang-char-util.h +++ b/source/core/slang-char-util.h @@ -3,7 +3,8 @@ #include "slang-string.h" -namespace Slang { +namespace Slang +{ struct CharUtil { @@ -12,12 +13,13 @@ struct CharUtil { enum Enum : Flags { - Upper = 0x01, ///< A-Z - Lower = 0x02, ///< a-z - Digit = 0x04, ///< 0-9 - HorizontalWhitespace = 0x08, ///< Whitespace that can appear horizontally (ie excluding CR/LF) - HexDigit = 0x10, ///< 0-9, a-f, A-F - VerticalWhitespace = 0x20, ///< \n \r + Upper = 0x01, ///< A-Z + Lower = 0x02, ///< a-z + Digit = 0x04, ///< 0-9 + HorizontalWhitespace = + 0x08, ///< Whitespace that can appear horizontally (ie excluding CR/LF) + HexDigit = 0x10, ///< 0-9, a-f, A-F + VerticalWhitespace = 0x20, ///< \n \r }; }; @@ -26,40 +28,62 @@ struct CharUtil SLANG_FORCE_INLINE static bool isUpper(char c) { return c >= 'A' && c <= 'Z'; } SLANG_FORCE_INLINE static bool isHorizontalWhitespace(char c) { return c == ' ' || c == '\t'; } SLANG_FORCE_INLINE static bool isVerticalWhitespace(char c) { return c == '\n' || c == '\r'; } - SLANG_FORCE_INLINE static bool isWhitespace(char c) { return (getFlags(c) & (Flag::HorizontalWhitespace | Flag::VerticalWhitespace)) != 0; } + SLANG_FORCE_INLINE static bool isWhitespace(char c) + { + return (getFlags(c) & (Flag::HorizontalWhitespace | Flag::VerticalWhitespace)) != 0; + } - /// True if it's alpha - SLANG_FORCE_INLINE static bool isAlpha(char c) { return (getFlags(c) & (Flag::Upper | Flag::Lower)) != 0; } - /// True if it's alpha or a digit - SLANG_FORCE_INLINE static bool isAlphaOrDigit(char c) { return (getFlags(c) & (Flag::Upper | Flag::Lower | Flag::Digit)) != 0; } + /// True if it's alpha + SLANG_FORCE_INLINE static bool isAlpha(char c) + { + return (getFlags(c) & (Flag::Upper | Flag::Lower)) != 0; + } + /// True if it's alpha or a digit + SLANG_FORCE_INLINE static bool isAlphaOrDigit(char c) + { + return (getFlags(c) & (Flag::Upper | Flag::Lower | Flag::Digit)) != 0; + } - /// True if the character is a valid hex character - SLANG_FORCE_INLINE static bool isHexDigit(char c) { return (getFlags(c) & Flag::HexDigit) != 0; } + /// True if the character is a valid hex character + SLANG_FORCE_INLINE static bool isHexDigit(char c) + { + return (getFlags(c) & Flag::HexDigit) != 0; + } - /// True if the character is an octal digit + /// True if the character is an octal digit SLANG_FORCE_INLINE static bool isOctalDigit(char c) { return c >= '0' && c <= '7'; } - /// For a given character get the associated flags + /// For a given character get the associated flags SLANG_FORCE_INLINE static Flags getFlags(char c) { return g_charFlagMap.flags[size_t(c)]; } - /// Given a character return the lower case equivalent - SLANG_FORCE_INLINE static char toLower(char c) { return (c >= 'A' && c <= 'Z') ? (c -'A' + 'a') : c; } - /// Given a character return the upper case equivalent - SLANG_FORCE_INLINE static char toUpper(char c) { return (c >= 'a' && c <= 'z') ? (c -'a' + 'A') : c; } + /// Given a character return the lower case equivalent + SLANG_FORCE_INLINE static char toLower(char c) + { + return (c >= 'A' && c <= 'Z') ? (c - 'A' + 'a') : c; + } + /// Given a character return the upper case equivalent + SLANG_FORCE_INLINE static char toUpper(char c) + { + return (c >= 'a' && c <= 'z') ? (c - 'a' + 'A') : c; + } - /// Given a value between 0-15 inclusive returns the hex digit. Uses lower case hex. - SLANG_FORCE_INLINE static char getHexChar(Index i) { SLANG_ASSERT((i & ~Index(0xf)) == 0); return char(i >= 10 ? (i - 10 + 'a') : (i + '0')); } + /// Given a value between 0-15 inclusive returns the hex digit. Uses lower case hex. + SLANG_FORCE_INLINE static char getHexChar(Index i) + { + SLANG_ASSERT((i & ~Index(0xf)) == 0); + return char(i >= 10 ? (i - 10 + 'a') : (i + '0')); + } - /// Returns the value if c interpretted as a decimal digit - /// If c is not a valid digit returns -1 + /// Returns the value if c interpretted as a decimal digit + /// If c is not a valid digit returns -1 inline static int getDecimalDigitValue(char c) { return isDigit(c) ? (c - '0') : -1; } - /// Returns the value if c interpretted as a hex digit - /// If c is not a valid hex returns -1 + /// Returns the value if c interpretted as a hex digit + /// If c is not a valid hex returns -1 inline static int getHexDigitValue(char c); - - /// Returns the value if c interpretted as a octal digit - /// If c is not a valid octal returns -1 + + /// Returns the value if c interpretted as a octal digit + /// If c is not a valid octal returns -1 inline static int getOctalDigitValue(char c) { return isOctalDigit(c) ? (c - '0') : -1; } struct CharFlagMap @@ -69,16 +93,17 @@ struct CharUtil static CharFlagMap makeCharFlagMap(); - // HACK! - // JS: Many of the inlined functions of CharUtil just access a global map. That referencing this global is *NOT* enough to - // link correctly with CharUtil on linux for a shared library. Caling this function can force linkage. + // HACK! + // JS: Many of the inlined functions of CharUtil just access a global map. That referencing this + // global is *NOT* enough to link correctly with CharUtil on linux for a shared library. Caling + // this function can force linkage. static int _ensureLink(); static const CharFlagMap g_charFlagMap; }; - + // ------------------------------------------------------------------------------------ -inline /* static */int CharUtil::getHexDigitValue(char c) +inline /* static */ int CharUtil::getHexDigitValue(char c) { if (c >= '0' && c <= '9') { diff --git a/source/core/slang-chunked-list.h b/source/core/slang-chunked-list.h index d414eaefb..95324f8c9 100644 --- a/source/core/slang-chunked-list.h +++ b/source/core/slang-chunked-list.h @@ -1,16 +1,15 @@ #ifndef SLANG_CORE_CHUNKED_LIST_H #define SLANG_CORE_CHUNKED_LIST_H -#include "slang.h" - #include "slang-allocator.h" #include "slang-array-view.h" #include "slang-math.h" +#include "slang.h" namespace Slang { // Items stored in a ChunkedList are guaranteed to have fixed address. -template +template class ChunkedList { private: @@ -21,10 +20,7 @@ private: uint32_t size = 0; uint32_t capacity = defaultChunkSize; Chunk* next = nullptr; - T* begin() - { - return reinterpret_cast(this + 1); - } + T* begin() { return reinterpret_cast(this + 1); } T* end() { return begin() + size; } }; @@ -60,24 +56,26 @@ private: public: typedef ChunkedList ThisType; ChunkedList() - : m_lastChunk(&m_firstChunk) - , m_count(0) - {} - template ChunkedList(const T& val, Args... args) { _init(val, args...); } + : m_lastChunk(&m_firstChunk), m_count(0) + { + } + template + ChunkedList(const T& val, Args... args) + { + _init(val, args...); + } ChunkedList(const ThisType& list) - : m_lastChunk(&m_firstChunk) - , m_count(0) + : m_lastChunk(&m_firstChunk), m_count(0) { this->operator=(list); } ChunkedList(ThisType&& list) - : m_lastChunk(&m_firstChunk) - , m_count(0) + : m_lastChunk(&m_firstChunk), m_count(0) { this->operator=(static_cast(list)); } ~ChunkedList() { _deallocateBuffer(); } - template + template ThisType& operator=(const ChunkedList& list) { clearAndDeallocate(); @@ -213,7 +211,8 @@ public: return result; } - template T* addRange(const TContainer& list) + template + T* addRange(const TContainer& list) { Chunk* chunk = _maybeReserveForAdd((uint32_t)list.getCount()); auto result = chunk->begin() + chunk->size; @@ -235,7 +234,6 @@ public: } private: - Index m_count = 0; ///< The amount of elements FirstChunk m_firstChunk; Chunk* m_lastChunk = &m_firstChunk; @@ -262,7 +260,8 @@ private: return AllocateMethod::deallocateArray(ptr, count); } - template void _init(const T& val, Args... args) + template + void _init(const T& val, Args... args) { add(val); _init(args...); diff --git a/source/core/slang-com-object.h b/source/core/slang-com-object.h index 617b7ccca..801af61a4 100644 --- a/source/core/slang-com-object.h +++ b/source/core/slang-com-object.h @@ -2,34 +2,35 @@ #define SLANG_COM_OBJECT_H #include "slang-basic.h" + #include namespace Slang { -/// A base class for COM interfaces that require atomic ref counting +/// A base class for COM interfaces that require atomic ref counting /// and are *NOT* derived from RefObject class ComBaseObject { public: - - /// If assigned the the ref count is *NOT* copied + /// If assigned the the ref count is *NOT* copied ComBaseObject& operator=(const ComBaseObject&) { return *this; } - /// Copy Ctor, does not copy ref count - ComBaseObject(const ComBaseObject&) : - m_refCount(0) - {} + /// Copy Ctor, does not copy ref count + ComBaseObject(const ComBaseObject&) + : m_refCount(0) + { + } - /// Default Ctor sets with no refs + /// Default Ctor sets with no refs ComBaseObject() : m_refCount(0) - {} + { + } - /// Dtor needs to be virtual to avoid needing to - /// Implement release for all derived types. - virtual ~ComBaseObject() - {} + /// Dtor needs to be virtual to avoid needing to + /// Implement release for all derived types. + virtual ~ComBaseObject() {} protected: inline uint32_t _releaseImpl(); @@ -50,7 +51,7 @@ inline uint32_t ComBaseObject::_releaseImpl() return count; } -#define SLANG_COM_BASE_IUNKNOWN_QUERY_INTERFACE \ +#define SLANG_COM_BASE_IUNKNOWN_QUERY_INTERFACE \ SLANG_NO_THROW SlangResult SLANG_MCALL queryInterface(SlangUUID const& uuid, void** outObject) \ SLANG_OVERRIDE \ { \ @@ -63,10 +64,16 @@ inline uint32_t ComBaseObject::_releaseImpl() } \ return SLANG_E_NO_INTERFACE; \ } -#define SLANG_COM_BASE_IUNKNOWN_ADD_REF \ - SLANG_NO_THROW uint32_t SLANG_MCALL addRef() SLANG_OVERRIDE { return ++m_refCount; } -#define SLANG_COM_BASE_IUNKNOWN_RELEASE \ - SLANG_NO_THROW uint32_t SLANG_MCALL release() SLANG_OVERRIDE { return _releaseImpl(); } +#define SLANG_COM_BASE_IUNKNOWN_ADD_REF \ + SLANG_NO_THROW uint32_t SLANG_MCALL addRef() SLANG_OVERRIDE \ + { \ + return ++m_refCount; \ + } +#define SLANG_COM_BASE_IUNKNOWN_RELEASE \ + SLANG_NO_THROW uint32_t SLANG_MCALL release() SLANG_OVERRIDE \ + { \ + return _releaseImpl(); \ + } #define SLANG_COM_BASE_IUNKNOWN_ALL \ SLANG_COM_BASE_IUNKNOWN_QUERY_INTERFACE \ SLANG_COM_BASE_IUNKNOWN_ADD_REF \ @@ -82,11 +89,12 @@ protected: public: ComObject() : comRefCount(0) - {} - ComObject(const ComObject& rhs) : - RefObject(rhs), - comRefCount(0) - {} + { + } + ComObject(const ComObject& rhs) + : RefObject(rhs), comRefCount(0) + { + } ComObject& operator=(const ComObject&) { return *this; } @@ -125,10 +133,16 @@ public: } \ return SLANG_E_NO_INTERFACE; \ } -#define SLANG_COM_OBJECT_IUNKNOWN_ADD_REF \ - SLANG_NO_THROW uint32_t SLANG_MCALL addRef() SLANG_OVERRIDE { return addRefImpl(); } -#define SLANG_COM_OBJECT_IUNKNOWN_RELEASE \ - SLANG_NO_THROW uint32_t SLANG_MCALL release() SLANG_OVERRIDE { return releaseImpl(); } +#define SLANG_COM_OBJECT_IUNKNOWN_ADD_REF \ + SLANG_NO_THROW uint32_t SLANG_MCALL addRef() SLANG_OVERRIDE \ + { \ + return addRefImpl(); \ + } +#define SLANG_COM_OBJECT_IUNKNOWN_RELEASE \ + SLANG_NO_THROW uint32_t SLANG_MCALL release() SLANG_OVERRIDE \ + { \ + return releaseImpl(); \ + } #define SLANG_COM_OBJECT_IUNKNOWN_ALL \ SLANG_COM_OBJECT_IUNKNOWN_QUERY_INTERFACE \ SLANG_COM_OBJECT_IUNKNOWN_ADD_REF \ diff --git a/source/core/slang-command-line.cpp b/source/core/slang-command-line.cpp index bfd9ed11a..8269d37c5 100644 --- a/source/core/slang-command-line.cpp +++ b/source/core/slang-command-line.cpp @@ -1,17 +1,17 @@ // slang-command-line.cpp #include "slang-command-line.h" +#include "slang-com-helper.h" #include "slang-process.h" - -#include "slang-string.h" #include "slang-string-escape-util.h" #include "slang-string-util.h" +#include "slang-string.h" -#include "slang-com-helper.h" - -namespace Slang { +namespace Slang +{ -/* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ExecutableLocation !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */ +/* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ExecutableLocation !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + */ void ExecutableLocation::set(const String& dir, const String& name) { diff --git a/source/core/slang-command-line.h b/source/core/slang-command-line.h index 163daf710..804266ad1 100644 --- a/source/core/slang-command-line.h +++ b/source/core/slang-command-line.h @@ -2,10 +2,11 @@ #ifndef SLANG_COMMAND_LINE_H #define SLANG_COMMAND_LINE_H -#include "slang-string.h" #include "slang-list.h" +#include "slang-string.h" -namespace Slang { +namespace Slang +{ struct ExecutableLocation { @@ -13,43 +14,67 @@ struct ExecutableLocation enum Type { - Unknown, ///< Not specified - Path, ///< The executable is set as a path (ie won't be searched for) - Name, ///< The executable is passed as a name which will be searched for + Unknown, ///< Not specified + Path, ///< The executable is set as a path (ie won't be searched for) + Name, ///< The executable is passed as a name which will be searched for }; - /// Set the executable path. - /// NOTE! On some targets the executable path *must* include an extension to be able to start as a process - void setPath(const String& path) { m_type = Type::Path; m_pathOrName = path; } + /// Set the executable path. + /// NOTE! On some targets the executable path *must* include an extension to be able to start as + /// a process + void setPath(const String& path) + { + m_type = Type::Path; + m_pathOrName = path; + } - /// Set a filename (such that the path will be looked up) - void setName(const String& filename) { m_type = Type::Name; m_pathOrName = filename; } + /// Set a filename (such that the path will be looked up) + void setName(const String& filename) + { + m_type = Type::Name; + m_pathOrName = filename; + } - void set(Type type, const String& pathOrName) { m_type = type; m_pathOrName = pathOrName; } + void set(Type type, const String& pathOrName) + { + m_type = type; + m_pathOrName = pathOrName; + } - /// Set the executable path from a base directory and an executable name (no suffix such as '.exe' needed) + /// Set the executable path from a base directory and an executable name (no suffix such as + /// '.exe' needed) void set(const String& dir, const String& name); - /// Determines if it's a name or a path when it sets + /// Determines if it's a name or a path when it sets void set(const String& nameOrPath); - /// Append as text to out. + /// Append as text to out. void append(StringBuilder& out) const; - /// Reset state to be same as ctor - void reset() { m_type = Type::Unknown; m_pathOrName = String(); } + /// Reset state to be same as ctor + void reset() + { + m_type = Type::Unknown; + m_pathOrName = String(); + } - /// Equality means exactly the same definition. - /// *NOT* that exactly the same executable is specified - bool operator==(const ThisType& rhs) const { return m_type == rhs.m_type && m_pathOrName == rhs.m_pathOrName; } + /// Equality means exactly the same definition. + /// *NOT* that exactly the same executable is specified + bool operator==(const ThisType& rhs) const + { + return m_type == rhs.m_type && m_pathOrName == rhs.m_pathOrName; + } bool operator!=(const ThisType& rhs) const { return !(*this == rhs); } ExecutableLocation() {} - ExecutableLocation(const String& dir, const String& name) { set(dir, name); } - ExecutableLocation(Type type, const String& pathOrName) : m_type(type), m_pathOrName(pathOrName) {} + ExecutableLocation(const String& dir, const String& name) { set(dir, name); } + ExecutableLocation(Type type, const String& pathOrName) + : m_type(type), m_pathOrName(pathOrName) + { + } explicit ExecutableLocation(const String& nameOrPath) { set(nameOrPath); } - + Type m_type = Type::Unknown; String m_pathOrName; }; @@ -58,42 +83,52 @@ struct CommandLine { typedef CommandLine ThisType; - /// Add args - assumed unescaped + /// Add args - assumed unescaped void addArg(const String& in) { m_args.add(in); } - void addArgs(const String* args, Int argsCount) { for (Int i = 0; i < argsCount; ++i) addArg(args[i]); } + void addArgs(const String* args, Int argsCount) + { + for (Int i = 0; i < argsCount; ++i) + addArg(args[i]); + } void addArgIfNotFound(const String& in); - /// Find the index of an arg which is exact match for slice - SLANG_INLINE Index findArgIndex(const UnownedStringSlice& slice) const { return m_args.indexOf(slice); } + /// Find the index of an arg which is exact match for slice + SLANG_INLINE Index findArgIndex(const UnownedStringSlice& slice) const + { + return m_args.indexOf(slice); + } - /// For handling args where the switch is placed directly in front of the path - void addPrefixPathArg(const char* prefix, const String& path, const char* pathPostfix = nullptr); + /// For handling args where the switch is placed directly in front of the path + void addPrefixPathArg( + const char* prefix, + const String& path, + const char* pathPostfix = nullptr); - /// Get the total number of args + /// Get the total number of args SLANG_FORCE_INLINE Index getArgCount() const { return m_args.getCount(); } - /// Reset to the initial state - void reset() { *this = CommandLine(); } + /// Reset to the initial state + void reset() { *this = CommandLine(); } - /// Append the args + /// Append the args void appendArgs(StringBuilder& out) const; - /// Append the command line to out + /// Append the command line to out void append(StringBuilder& out) const; - /// convert into a string + /// convert into a string String toString() const; - /// Convert just the args to string + /// Convert just the args to string String toStringArgs() const; - /// Set an executable location + /// Set an executable location void setExecutableLocation(const ExecutableLocation& loc) { m_executableLocation = loc; } - ExecutableLocation m_executableLocation; ///< The executable location - List m_args; ///< The arguments (Stored *unescaped*) + ExecutableLocation m_executableLocation; ///< The executable location + List m_args; ///< The arguments (Stored *unescaped*) }; -} +} // namespace Slang #endif // SLANG_COMMAND_LINE_H diff --git a/source/core/slang-command-options-writer.cpp b/source/core/slang-command-options-writer.cpp index afa46db64..f46bcc56c 100644 --- a/source/core/slang-command-options-writer.cpp +++ b/source/core/slang-command-options-writer.cpp @@ -2,18 +2,26 @@ #include "slang-command-options-writer.h" -#include "slang-string-util.h" -#include "slang-char-util.h" #include "slang-byte-encode-util.h" +#include "slang-char-util.h" +#include "slang-string-util.h" + +namespace Slang +{ -namespace Slang { - -namespace { // anonymous +namespace +{ // anonymous typedef CommandOptionsWriter::Style Style; -} // anonymous +} // namespace -static bool _isMarkdown(Style style) { return style == Style::Markdown || style == Style::NoLinkMarkdown; } -static bool _hasLinks(Style style) { return style == Style::Markdown; } +static bool _isMarkdown(Style style) +{ + return style == Style::Markdown || style == Style::NoLinkMarkdown; +} +static bool _hasLinks(Style style) +{ + return style == Style::Markdown; +} /* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!! MarkdownCommandOptionsWriter !!!!!!!!!!!!!!!!!!!!!!!!!!! */ @@ -25,17 +33,17 @@ public: typedef uint32_t LinkFlags; struct LinkFlag { - enum Enum + enum Enum { Category = 0x1, - Option = 0x2, + Option = 0x2, All = Category | Option, }; }; - MarkdownCommandOptionsWriter(const Options& options): - Super(options) + MarkdownCommandOptionsWriter(const Options& options) + : Super(options) { } @@ -45,15 +53,17 @@ protected: virtual void appendDescriptionImpl() SLANG_OVERRIDE; void _appendParagraph(const UnownedStringSlice& text, LinkFlags flags = LinkFlag::All); - void _appendParagraph(const ConstArrayView& words, LinkFlags flags = LinkFlag::All); + void _appendParagraph( + const ConstArrayView& words, + LinkFlags flags = LinkFlag::All); - void _appendMaybeLink(const UnownedStringSlice& word, LinkFlags linkFlags); + void _appendMaybeLink(const UnownedStringSlice& word, LinkFlags linkFlags); void _appendText(const UnownedStringSlice& text); void _appendDescriptionForCategory(Index categoryIndex); UnownedStringSlice _getLinkName(CommandOptions::LookupKind kind, Index index); UnownedStringSlice _getLinkName(const NameKey& key, Index index); - + void _appendQuickLinks(); bool m_hasLinks = false; @@ -91,15 +101,15 @@ static bool _needsMarkdownEscape(const UnownedStringSlice& text) { switch (c) { - case '<': - case '>': - case '&': - case '[': - case ']': + case '<': + case '>': + case '&': + case '[': + case ']': { return true; } - default: break; + default: break; } } @@ -115,12 +125,12 @@ void _appendEscapedMarkdown(const UnownedStringSlice& text, StringBuilder& ioBuf { switch (c) { - case '<': ioBuf << "<"; break; - case '>': ioBuf << ">"; break; - case '&': ioBuf << "&"; break; - case '[': ioBuf << "\\["; break; - case ']': ioBuf << "\\]"; break; - default: ioBuf << c; + case '<': ioBuf << "<"; break; + case '>': ioBuf << ">"; break; + case '&': ioBuf << "&"; break; + case '[': ioBuf << "\\["; break; + case ']': ioBuf << "\\]"; break; + default: ioBuf << c; } } } @@ -149,7 +159,9 @@ void MarkdownCommandOptionsWriter::_appendQuickLinks() m_builder << "\n"; } -void MarkdownCommandOptionsWriter::_appendParagraph(const UnownedStringSlice& text, LinkFlags linkFlags) +void MarkdownCommandOptionsWriter::_appendParagraph( + const UnownedStringSlice& text, + LinkFlags linkFlags) { List words; StringUtil::splitOnWhitespace(text, words); @@ -171,12 +183,16 @@ static UnownedStringSlice _trimPunctuation(const UnownedStringSlice& word) const char* start = word.begin(); const char* end = word.end(); - while (start < end && _isStartPunctionation(*start)) start++; - while (end > start && _isEndPunctionation(end[-1])) --end; + while (start < end && _isStartPunctionation(*start)) + start++; + while (end > start && _isEndPunctionation(end[-1])) + --end; return UnownedStringSlice(start, end); } -void MarkdownCommandOptionsWriter::_appendMaybeLink(const UnownedStringSlice& inWord, LinkFlags linkFlags) +void MarkdownCommandOptionsWriter::_appendMaybeLink( + const UnownedStringSlice& inWord, + LinkFlags linkFlags) { if (linkFlags) { @@ -190,17 +206,27 @@ void MarkdownCommandOptionsWriter::_appendMaybeLink(const UnownedStringSlice& in // Look for options if (trimmedWord[0] == '-' && (linkFlags & LinkFlag::Option)) { - index = m_commandOptions->findTargetIndexByName(LookupKind::Option, trimmedWord, &nameKey); + index = m_commandOptions->findTargetIndexByName( + LookupKind::Option, + trimmedWord, + &nameKey); } - else if (trimmedWord[0] == '<' && trimmedWord[trimmedWord.getLength() - 1] == '>' && (linkFlags & LinkFlag::Category)) + else if ( + trimmedWord[0] == '<' && trimmedWord[trimmedWord.getLength() - 1] == '>' && + (linkFlags & LinkFlag::Category)) { - index = m_commandOptions->findTargetIndexByName(LookupKind::Category, trimmedWord.subString(1, trimmedWord.getLength() - 2), &nameKey); + index = m_commandOptions->findTargetIndexByName( + LookupKind::Category, + trimmedWord.subString(1, trimmedWord.getLength() - 2), + &nameKey); } - + if (index > 0) { // Append before the link - _appendEscapedMarkdown(UnownedStringSlice(inWord.begin(), trimmedWord.begin()), m_builder); + _appendEscapedMarkdown( + UnownedStringSlice(inWord.begin(), trimmedWord.begin()), + m_builder); // Make into a link m_builder << "["; @@ -208,7 +234,9 @@ void MarkdownCommandOptionsWriter::_appendMaybeLink(const UnownedStringSlice& in m_builder << "](#" << _getLinkName(nameKey, index) << ")"; // Append after the link - _appendEscapedMarkdown(UnownedStringSlice(trimmedWord.end(), inWord.end()), m_builder); + _appendEscapedMarkdown( + UnownedStringSlice(trimmedWord.end(), inWord.end()), + m_builder); return; } } @@ -217,7 +245,9 @@ void MarkdownCommandOptionsWriter::_appendMaybeLink(const UnownedStringSlice& in _appendEscapedMarkdown(inWord, m_builder); } -void MarkdownCommandOptionsWriter::_appendParagraph(const ConstArrayView& words, LinkFlags linkFlags) +void MarkdownCommandOptionsWriter::_appendParagraph( + const ConstArrayView& words, + LinkFlags linkFlags) { if (m_hasLinks && linkFlags) { @@ -271,19 +301,21 @@ void MarkdownCommandOptionsWriter::_appendDescriptionForCategory(Index categoryI if (m_hasLinks) { // Output anchor - m_builder << "\n"; + m_builder << "\n"; } m_builder << "# " << category.name << "\n\n"; - + // If there is a description output, making \n split paragraphs if (category.description.getLength() > 0) { _appendText(category.description); - } + } } - for (Index optionIndex = category.optionStartIndex; optionIndex < category.optionEndIndex; ++optionIndex) + for (Index optionIndex = category.optionStartIndex; optionIndex < category.optionEndIndex; + ++optionIndex) { const auto& option = options.getOptionAt(optionIndex); @@ -294,7 +326,7 @@ void MarkdownCommandOptionsWriter::_appendDescriptionForCategory(Index categoryI if (isValue) { m_builder << "* "; - // Output all the names + // Output all the names m_builder << "`"; StringUtil::join(names.getBuffer(), names.getCount(), toSlice("`, `"), m_builder); m_builder << "` "; @@ -303,7 +335,8 @@ void MarkdownCommandOptionsWriter::_appendDescriptionForCategory(Index categoryI { if (m_hasLinks) { - m_builder << "\n"; + m_builder << "\n"; } m_builder << "## "; @@ -322,17 +355,24 @@ void MarkdownCommandOptionsWriter::_appendDescriptionForCategory(Index categoryI const char* cur = option.usage.begin(); for (auto usedCategory : usedCategories) { - _appendEscapedMarkdown(UnownedStringSlice(cur, usedCategory.begin()), m_builder); + _appendEscapedMarkdown( + UnownedStringSlice(cur, usedCategory.begin()), + m_builder); // Now do the link - const Index usedCategoryIndex = options.findCategoryByName(usedCategory); + const Index usedCategoryIndex = + options.findCategoryByName(usedCategory); - m_builder << "[" << usedCategory << "](#" << _getLinkName(LookupKind::Category, usedCategoryIndex) << ")"; + m_builder << "[" << usedCategory << "](#" + << _getLinkName(LookupKind::Category, usedCategoryIndex) + << ")"; cur = usedCategory.end(); } - _appendEscapedMarkdown(UnownedStringSlice(cur, option.usage.end()), m_builder); + _appendEscapedMarkdown( + UnownedStringSlice(cur, option.usage.end()), + m_builder); } else { @@ -370,9 +410,9 @@ UnownedStringSlice MarkdownCommandOptionsWriter::_getLinkName(const NameKey& key return m_pool.getSlice(*ptr); } - UnownedStringSlice prefix = (key.kind == CommandOptions::LookupKind::Category) ? - m_commandOptions->getFirstNameForCategory(index) : - m_commandOptions->getFirstNameForOption(index); + UnownedStringSlice prefix = (key.kind == CommandOptions::LookupKind::Category) + ? m_commandOptions->getFirstNameForCategory(index) + : m_commandOptions->getFirstNameForOption(index); prefix = prefix.trim('-'); if (prefix.getLength() == 0) @@ -406,17 +446,17 @@ UnownedStringSlice MarkdownCommandOptionsWriter::_getLinkName(const NameKey& key return m_pool.getSlice(handle); } -UnownedStringSlice MarkdownCommandOptionsWriter::_getLinkName(CommandOptions::LookupKind kind, Index index) +UnownedStringSlice MarkdownCommandOptionsWriter::_getLinkName( + CommandOptions::LookupKind kind, + Index index) { auto& options = *m_commandOptions; - // Set up the name key - const auto key = (kind == LookupKind::Category) ? - options.getNameKeyForCategory(index) : - options.getNameKeyForOption(index); - - return _getLinkName(key, index); + // Set up the name key + const auto key = (kind == LookupKind::Category) ? options.getNameKeyForCategory(index) + : options.getNameKeyForOption(index); + return _getLinkName(key, index); } /* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!! TextCommandOptionsWriter !!!!!!!!!!!!!!!!!!!!!!!!!!! */ @@ -425,11 +465,12 @@ class TextCommandOptionsWriter : public CommandOptionsWriter { public: typedef CommandOptionsWriter Super; - - TextCommandOptionsWriter(const Options& options) : - Super(options) + + TextCommandOptionsWriter(const Options& options) + : Super(options) { } + protected: // CommandOptionsWriter virtual void appendDescriptionForCategoryImpl(Index categoryIndex) SLANG_OVERRIDE; @@ -580,26 +621,24 @@ void TextCommandOptionsWriter::_appendText(Count indentCount, const UnownedStrin typedef CommandOptionsWriter::Style Style; -static const NamesDescriptionValue s_styleInfos[] = -{ - { ValueInt(Style::Text), "text", "Text suitable for output to a terminal" }, - { ValueInt(Style::Markdown), "markdown", "Markdown" }, - { ValueInt(Style::NoLinkMarkdown), "no-link-markdown", "Markdown without links" }, +static const NamesDescriptionValue s_styleInfos[] = { + {ValueInt(Style::Text), "text", "Text suitable for output to a terminal"}, + {ValueInt(Style::Markdown), "markdown", "Markdown"}, + {ValueInt(Style::NoLinkMarkdown), "no-link-markdown", "Markdown without links"}, }; -/* static */ConstArrayView CommandOptionsWriter::getStyleInfos() +/* static */ ConstArrayView CommandOptionsWriter::getStyleInfos() { return makeConstArrayView(s_styleInfos); } -CommandOptionsWriter::CommandOptionsWriter(const Options& options) : - m_pool(StringSlicePool::Style::Default), - m_options(options) +CommandOptionsWriter::CommandOptionsWriter(const Options& options) + : m_pool(StringSlicePool::Style::Default), m_options(options) { m_options.indent = m_pool.addAndGetSlice(options.indent); } -/* static */RefPtr CommandOptionsWriter::create(const Options& options) +/* static */ RefPtr CommandOptionsWriter::create(const Options& options) { if (_isMarkdown(options.style)) { @@ -611,7 +650,9 @@ CommandOptionsWriter::CommandOptionsWriter(const Options& options) : } } -void CommandOptionsWriter::appendDescriptionForCategory(CommandOptions* options, Index categoryIndex) +void CommandOptionsWriter::appendDescriptionForCategory( + CommandOptions* options, + Index categoryIndex) { m_commandOptions = options; appendDescriptionForCategoryImpl(categoryIndex); @@ -667,7 +708,10 @@ void CommandOptionsWriter::_requireIndent(Count indentCount) } } -void CommandOptionsWriter::_appendWrappedIndented(Count indentCount, List& slices, const UnownedStringSlice& delimit) +void CommandOptionsWriter::_appendWrappedIndented( + Count indentCount, + List& slices, + const UnownedStringSlice& delimit) { Count lineLength = _getCurrentLineLength(); @@ -708,5 +752,3 @@ void CommandOptionsWriter::_appendWrappedIndented(Count indentCount, List getStyleInfos(); struct Options { - Style style = Style::Text; ///< The style - Index lineLength = 120; ///< The maximum amount of characters on a line - UnownedStringSlice indent = toSlice(" ");; + Style style = Style::Text; ///< The style + Index lineLength = 120; ///< The maximum amount of characters on a line + UnownedStringSlice indent = toSlice(" "); + ; }; - /// Append descirption for a category + /// Append descirption for a category void appendDescriptionForCategory(CommandOptions* options, Index categoryIndex); - /// Appends a description of all of the options + /// Appends a description of all of the options void appendDescription(CommandOptions* options); - /// Get the builder that string is being written to + /// Get the builder that string is being written to StringBuilder& getBuilder() { return m_builder; } static RefPtr create(const Options& options); - -protected: - /// Append descirption for a category +protected: + /// Append descirption for a category virtual void appendDescriptionForCategoryImpl(Index categoryIndex) = 0; - /// Appends a description of all of the options + /// Appends a description of all of the options virtual void appendDescriptionImpl() = 0; // Ctor, use create to create a writer CommandOptionsWriter(const Options& options); - /// Get the length of the current line in ascii chars/bytes + /// Get the length of the current line in ascii chars/bytes Count _getCurrentLineLength(); - /// Indentation/wrapping + /// Indentation/wrapping void _requireIndent(Count indentCount); - void _appendWrappedIndented(Count indentCount, List& slices, const UnownedStringSlice& delimit); - + void _appendWrappedIndented( + Count indentCount, + List& slices, + const UnownedStringSlice& delimit); + CommandOptions* m_commandOptions = nullptr; - StringSlicePool m_pool; + StringSlicePool m_pool; StringBuilder m_builder; Options m_options; }; } // namespace Slang -#endif +#endif diff --git a/source/core/slang-command-options.cpp b/source/core/slang-command-options.cpp index 5bbe59a0d..a4bb8b552 100644 --- a/source/core/slang-command-options.cpp +++ b/source/core/slang-command-options.cpp @@ -2,11 +2,12 @@ #include "slang-command-options.h" -#include "slang-string-util.h" -#include "slang-char-util.h" #include "slang-byte-encode-util.h" +#include "slang-char-util.h" +#include "slang-string-util.h" -namespace Slang { +namespace Slang +{ UnownedStringSlice CommandOptions::getFirstNameForOption(Index optionIndex) { @@ -26,7 +27,8 @@ CommandOptions::NameKey CommandOptions::getNameKeyForOption(Index optionIndex) const auto& cat = m_categories[opt.categoryIndex]; NameKey key; key.nameIndex = m_pool.findIndex(getFirstNameForOption(optionIndex)); - key.kind = (cat.kind == CategoryKind::Option) ? LookupKind::Option : makeLookupKind(opt.categoryIndex); + key.kind = + (cat.kind == CategoryKind::Option) ? LookupKind::Option : makeLookupKind(opt.categoryIndex); return key; } @@ -38,7 +40,10 @@ CommandOptions::NameKey CommandOptions::getNameKeyForCategory(Index categoryInde return key; } -SlangResult CommandOptions::_addName(LookupKind kind, const UnownedStringSlice& name, Index targetIndex) +SlangResult CommandOptions::_addName( + LookupKind kind, + const UnownedStringSlice& name, + Index targetIndex) { NameKey nameKey; nameKey.kind = kind; @@ -52,7 +57,10 @@ SlangResult CommandOptions::_addName(LookupKind kind, const UnownedStringSlice& return SLANG_OK; } -SlangResult CommandOptions::_addOptionName(const UnownedStringSlice& name, Flags flags, Index targetIndex) +SlangResult CommandOptions::_addOptionName( + const UnownedStringSlice& name, + Flags flags, + Index targetIndex) { SLANG_RETURN_ON_FAIL(_addName(LookupKind::Option, name, targetIndex)); @@ -67,7 +75,10 @@ SlangResult CommandOptions::_addOptionName(const UnownedStringSlice& name, Flags return SLANG_OK; } -SlangResult CommandOptions::_addValueName(const UnownedStringSlice& name, Index categoryIndex, Index optionIndex) +SlangResult CommandOptions::_addValueName( + const UnownedStringSlice& name, + Index categoryIndex, + Index optionIndex) { return _addName(LookupKind(categoryIndex), name, optionIndex); } @@ -122,7 +133,10 @@ Index CommandOptions::_addOption(const UnownedStringSlice& name, const Option& i } } -Index CommandOptions::_addOption(const UnownedStringSlice* names, Count namesCount, const Option& inOption) +Index CommandOptions::_addOption( + const UnownedStringSlice* names, + Count namesCount, + const Option& inOption) { SLANG_ASSERT(namesCount > 0); SLANG_ASSERT(inOption.categoryIndex >= 0); @@ -134,7 +148,8 @@ Index CommandOptions::_addOption(const UnownedStringSlice* names, Count namesCou auto& cat = m_categories[inOption.categoryIndex]; - // If there are already options associated with this category, we have to be in the run of the last ones added + // If there are already options associated with this category, we have to be in the run of the + // last ones added if (cat.optionStartIndex != cat.optionEndIndex) { // If we aren't at the end then this is an error @@ -172,9 +187,10 @@ Index CommandOptions::_addOption(const UnownedStringSlice* names, Count namesCou { for (Index i = 0; i < namesCount; ++i) { - _addValueName(names[i], inOption.categoryIndex, optionIndex); + _addValueName(names[i], inOption.categoryIndex, optionIndex); } - if (SLANG_FAILED(_addUserValue(LookupKind(inOption.categoryIndex), inOption.userValue, optionIndex))) + if (SLANG_FAILED( + _addUserValue(LookupKind(inOption.categoryIndex), inOption.userValue, optionIndex))) { return -1; } @@ -198,7 +214,7 @@ Index CommandOptions::_addOption(const UnownedStringSlice* names, Count namesCou // Set the end index cat.optionEndIndex = optionIndex + 1; - + return optionIndex; } @@ -219,7 +235,11 @@ static void _handlePostFix(UnownedStringSlice& ioSlice, CommandOptions::Flags& i } } -void CommandOptions::add(const char* inName, const char* usage, const char* description, UserValue userValue) +void CommandOptions::add( + const char* inName, + const char* usage, + const char* description, + UserValue userValue) { UnownedStringSlice nameSlice(inName); @@ -250,7 +270,13 @@ void CommandOptions::add(const char* inName, const char* usage, const char* desc } } -void CommandOptions::add(const UnownedStringSlice* names, Count namesCount, const char* usage, const char* description, UserValue userValue, Flags flags) +void CommandOptions::add( + const UnownedStringSlice* names, + Count namesCount, + const char* usage, + const char* description, + UserValue userValue, + Flags flags) { Option option; option.categoryIndex = m_currentCategoryIndex; @@ -337,7 +363,10 @@ void CommandOptions::addValue(const UnownedStringSlice& name, UserValue userValu _addValue(name, option); } -void CommandOptions::addValue(const UnownedStringSlice& name, const UnownedStringSlice& description, UserValue userValue) +void CommandOptions::addValue( + const UnownedStringSlice& name, + const UnownedStringSlice& description, + UserValue userValue) { Option option; option.categoryIndex = m_currentCategoryIndex; @@ -346,7 +375,10 @@ void CommandOptions::addValue(const UnownedStringSlice& name, const UnownedStrin _addValue(name, option); } -void CommandOptions::addValue(const UnownedStringSlice* names, Count namesCount, UserValue userValue) +void CommandOptions::addValue( + const UnownedStringSlice* names, + Count namesCount, + UserValue userValue) { Option option; option.categoryIndex = m_currentCategoryIndex; @@ -377,7 +409,11 @@ void CommandOptions::addValue(const char* name, UserValue userValue) addValue(UnownedStringSlice(name), userValue); } -Index CommandOptions::addCategory(CategoryKind kind, const char* name, const char* description, UserValue userValue) +Index CommandOptions::addCategory( + CategoryKind kind, + const char* name, + const char* description, + UserValue userValue) { const UnownedStringSlice nameSlice(name); @@ -425,7 +461,10 @@ void CommandOptions::setCategory(const char* name) m_currentCategoryIndex = -1; } -Index CommandOptions::findTargetIndexByName(LookupKind kind, const UnownedStringSlice& name, NameKey* outNameKey) const +Index CommandOptions::findTargetIndexByName( + LookupKind kind, + const UnownedStringSlice& name, + NameKey* outNameKey) const { // Look up directly { @@ -470,7 +509,10 @@ Index CommandOptions::findTargetIndexByName(LookupKind kind, const UnownedString return -1; } -Index CommandOptions::_findTargetIndexByName(LookupKind kind, const UnownedStringSlice& name, NameKey* outNameKey) const +Index CommandOptions::_findTargetIndexByName( + LookupKind kind, + const UnownedStringSlice& name, + NameKey* outNameKey) const { const auto nameIndex = m_pool.findIndex(name); // If the name isn't in the pool then there isn't a category with this name @@ -524,7 +566,9 @@ Index CommandOptions::findCategoryByCaseInsensitiveName(const UnownedStringSlice return -1; } -Index CommandOptions::findOptionByCategoryUserValue(UserValue categoryUserValue, const UnownedStringSlice& name) const +Index CommandOptions::findOptionByCategoryUserValue( + UserValue categoryUserValue, + const UnownedStringSlice& name) const { Index categoryIndex = findTargetIndexByUserValue(LookupKind::Category, categoryUserValue); if (categoryIndex < 0) @@ -535,14 +579,19 @@ Index CommandOptions::findOptionByCategoryUserValue(UserValue categoryUserValue, return findValueByName(categoryIndex, name); } -ConstArrayView CommandOptions::getOptionsForCategory(Index categoryIndex) const +ConstArrayView CommandOptions::getOptionsForCategory( + Index categoryIndex) const { const auto& cat = m_categories[categoryIndex]; - return makeConstArrayView(m_options.getBuffer() + cat.optionStartIndex, cat.optionEndIndex - cat.optionStartIndex); + return makeConstArrayView( + m_options.getBuffer() + cat.optionStartIndex, + cat.optionEndIndex - cat.optionStartIndex); } -void CommandOptions::appendCategoryOptionNames(Index categoryIndex, List& outNames) const +void CommandOptions::appendCategoryOptionNames( + Index categoryIndex, + List& outNames) const { for (const auto& option : getOptionsForCategory(categoryIndex)) { @@ -550,28 +599,33 @@ void CommandOptions::appendCategoryOptionNames(Index categoryIndex, List& outNames) const +void CommandOptions::getCategoryOptionNames(Index categoryIndex, List& outNames) + const { outNames.clear(); appendCategoryOptionNames(categoryIndex, outNames); } -void CommandOptions::splitUsage(const UnownedStringSlice& usageSlice, List& outSlices) const +void CommandOptions::splitUsage( + const UnownedStringSlice& usageSlice, + List& outSlices) const { const auto* cur = usageSlice.begin(); const auto* end = usageSlice.end(); while (cur < end) { - // Find < - while (cur < end && *cur != '<') cur++; + // Find < + while (cur < end && *cur != '<') + cur++; // If we found it look for the end if (cur < end && *cur == '<') { ++cur; auto start = cur; - while (cur < end && (CharUtil::isAlphaOrDigit(*cur) || *cur == '-' || *cur == '_') && *cur != '>') + while (cur < end && (CharUtil::isAlphaOrDigit(*cur) || *cur == '-' || *cur == '_') && + *cur != '>') { cur++; } @@ -594,7 +648,9 @@ void CommandOptions::splitUsage(const UnownedStringSlice& usageSlice, List& outCategories) const +void CommandOptions::findCategoryIndicesFromUsage( + const UnownedStringSlice& slice, + List& outCategories) const { List categoryNames; splitUsage(slice, categoryNames); @@ -609,7 +665,10 @@ void CommandOptions::findCategoryIndicesFromUsage(const UnownedStringSlice& slic } } -Count CommandOptions::getOptionCountInRange(Index categoryIndex, UserValue start, UserValue nonInclEnd) const +Count CommandOptions::getOptionCountInRange( + Index categoryIndex, + UserValue start, + UserValue nonInclEnd) const { const UserIndex startIndex = UserIndex(start); const UserIndex endIndex = UserIndex(nonInclEnd); @@ -631,7 +690,8 @@ Count CommandOptions::getOptionCountInRange(Index categoryIndex, UserValue start return count; } -Count CommandOptions::getOptionCountInRange(LookupKind kind, UserValue start, UserValue nonInclEnd) const +Count CommandOptions::getOptionCountInRange(LookupKind kind, UserValue start, UserValue nonInclEnd) + const { Index count = 0; @@ -671,7 +731,10 @@ Count CommandOptions::getOptionCountInRange(LookupKind kind, UserValue start, Us } -bool CommandOptions::hasContiguousUserValueRange(LookupKind kind, UserValue start, UserValue nonInclEnd) const +bool CommandOptions::hasContiguousUserValueRange( + LookupKind kind, + UserValue start, + UserValue nonInclEnd) const { const Count rangeCount = Count(nonInclEnd) - Count(start); SLANG_ASSERT(rangeCount >= 0); @@ -686,5 +749,3 @@ bool CommandOptions::hasContiguousUserValueRange(LookupKind kind, UserValue star } } // namespace Slang - - diff --git a/source/core/slang-command-options.h b/source/core/slang-command-options.h index 8b6d7b0ce..9d7af44d9 100644 --- a/source/core/slang-command-options.h +++ b/source/core/slang-command-options.h @@ -2,13 +2,13 @@ #define SLANG_CORE_COMMAND_OPTIONS_H #include "slang-basic.h" -#include "slang-string-slice-pool.h" #include "slang-name-value.h" +#include "slang-string-slice-pool.h" namespace Slang { -/* For convenience we encode within "names" flags. +/* For convenience we encode within "names" flags. "-D..." means that -D *must* be followed by the value "-D?..." means that -D *can* be a prefix, or it might be followed with the arg */ @@ -23,29 +23,36 @@ struct CommandOptions enum class LookupKind : int32_t { - Category = -2, ///< Lookup a category name - Option = -1, ///< Lookup an option name (all options use the same lookup index even if in different categories) - Base = 0, ///< Lookup via category index + Category = -2, ///< Lookup a category name + Option = -1, ///< Lookup an option name (all options use the same lookup index even if in + ///< different categories) + Base = 0, ///< Lookup via category index }; - /// A key type that uses the combination of the lookup kind and a name index. - /// Maps to a target index that could be a category or an option index. + /// A key type that uses the combination of the lookup kind and a name index. + /// Maps to a target index that could be a category or an option index. struct NameKey { typedef NameKey ThisType; - SLANG_FORCE_INLINE bool operator==(const ThisType& rhs) const { return kind == rhs.kind && nameIndex == rhs.nameIndex; } + SLANG_FORCE_INLINE bool operator==(const ThisType& rhs) const + { + return kind == rhs.kind && nameIndex == rhs.nameIndex; + } SLANG_FORCE_INLINE bool operator!=(const ThisType& rhs) const { return !(*this == rhs); } - HashCode getHashCode() const { return combineHash(Slang::getHashCode(kind), Slang::getHashCode(nameIndex)); } + HashCode getHashCode() const + { + return combineHash(Slang::getHashCode(kind), Slang::getHashCode(nameIndex)); + } - LookupKind kind; ///< The kind of lookup - Index nameIndex; ///< The name index in the pool + LookupKind kind; ///< The kind of lookup + Index nameIndex; ///< The name index in the pool }; enum class CategoryKind { - Option, ///< Command line option (like "-D") - Value, ///< One of a set of values (such as an enum or some other kind of list of values) + Option, ///< Command line option (like "-D") + Value, ///< One of a set of values (such as an enum or some other kind of list of values) }; struct ValuePair @@ -71,128 +78,179 @@ struct CommandOptions { enum Enum : Flags { - CanPrefix = 0x1, /// Allows -Dfsggf or -D fdsfsd - IsPrefix = 0x2, /// Is an option that can only be a prefix + CanPrefix = 0x1, /// Allows -Dfsggf or -D fdsfsd + IsPrefix = 0x2, /// Is an option that can only be a prefix }; }; struct Option { - UnownedStringSlice names; ///< Comma delimited list of names, first name is the default - UnownedStringSlice usage; ///< Describes usage, can be empty - UnownedStringSlice description; ///< A description of usage + UnownedStringSlice names; ///< Comma delimited list of names, first name is the default + UnownedStringSlice usage; ///< Describes usage, can be empty + UnownedStringSlice description; ///< A description of usage UserValue userValue = kInvalidUserValue; - Index categoryIndex = -1; ///< Category this option belongs to - Flags flags = 0; ///< Flags about this option + Index categoryIndex = -1; ///< Category this option belongs to + Flags flags = 0; ///< Flags about this option }; - /// Get the first name + /// Get the first name UnownedStringSlice getFirstNameForOption(Index optionIndex); - /// Get the first name for the category + /// Get the first name for the category UnownedStringSlice getFirstNameForCategory(Index categoryIndex); - /// Get a name key for an opton + /// Get a name key for an opton NameKey getNameKeyForOption(Index optionIndex); - /// Get a name key for a category + /// Get a name key for a category NameKey getNameKeyForCategory(Index optionIndex); - /// Add a category - Index addCategory(CategoryKind kind, const char* name, const char* description, UserValue userValue = kInvalidUserValue); - /// Use an already known category. It's an error if the category isn't found + /// Add a category + Index addCategory( + CategoryKind kind, + const char* name, + const char* description, + UserValue userValue = kInvalidUserValue); + /// Use an already known category. It's an error if the category isn't found void setCategory(const char* name); - void add(const char* name, const char* usage, const char* description, UserValue userValue = kInvalidUserValue); - void add(const UnownedStringSlice* names, Count namesCount, const char* usage, const char* description, UserValue userValue = kInvalidUserValue, Flags flags = 0); + void add( + const char* name, + const char* usage, + const char* description, + UserValue userValue = kInvalidUserValue); + void add( + const UnownedStringSlice* names, + Count namesCount, + const char* usage, + const char* description, + UserValue userValue = kInvalidUserValue, + Flags flags = 0); void addValue(const UnownedStringSlice& name, UserValue userValue = kInvalidUserValue); - void addValue(const UnownedStringSlice& name, const UnownedStringSlice& description, UserValue userValue = kInvalidUserValue); - void addValue(const char* name, const char* description, UserValue userValue = kInvalidUserValue); + void addValue( + const UnownedStringSlice& name, + const UnownedStringSlice& description, + UserValue userValue = kInvalidUserValue); + void addValue( + const char* name, + const char* description, + UserValue userValue = kInvalidUserValue); void addValue(const char* name, UserValue userValue = kInvalidUserValue); - void addValue(const UnownedStringSlice* names, Count namesCount, UserValue userValue = kInvalidUserValue); + void addValue( + const UnownedStringSlice* names, + Count namesCount, + UserValue userValue = kInvalidUserValue); - /// Add values (without UserValue association) + /// Add values (without UserValue association) void addValues(const ValuePair* pairs, Count pairsCount); - /// Add values + /// Add values void addValues(const ConstArrayView& values); void addValues(const ConstArrayView& values); void addValues(const ConstArrayView& values); - /// Sometimes values are listed with *names* per value. This method will take into account the aliases + /// Sometimes values are listed with *names* per value. This method will take into account the + /// aliases void addValuesWithAliases(const ConstArrayView& values); - /// Get the target index based off the name and the kind - Index findTargetIndexByName(LookupKind kind, const UnownedStringSlice& name, NameKey* outNameKey = nullptr) const; - /// Given a kind and a user value lookup the target index + /// Get the target index based off the name and the kind + Index findTargetIndexByName( + LookupKind kind, + const UnownedStringSlice& name, + NameKey* outNameKey = nullptr) const; + /// Given a kind and a user value lookup the target index Index findTargetIndexByUserValue(LookupKind kind, UserValue userValue) const; - /// Finds the category by name or -1 if not found - Index findCategoryByName(const UnownedStringSlice& name) const { return findTargetIndexByName(LookupKind::Category, name); } - /// Finds the option index by name or -1 if not found - Index findOptionByName(const UnownedStringSlice& name) const { return findTargetIndexByName(LookupKind::Option, name); } - /// Find the option index of a value, using it's category index and the name - Index findValueByName(Index categoryIndex, const UnownedStringSlice& name) const { return findTargetIndexByName(LookupKind(categoryIndex), name); } - - /// Get the category index from a user value - Index findCategoryByUserValue(UserValue userValue) const { return findTargetIndexByUserValue(LookupKind::Category, userValue); } - /// Can only get options - Index findOptionByUserValue(UserValue userValue) const { return findTargetIndexByUserValue(LookupKind::Option, userValue); } - /// Get a value associated with a category - Index findValueByUserValue(Index categoryIndex, UserValue userValue) const { return findTargetIndexByUserValue(LookupKind(categoryIndex), userValue); } - - /// Given a category user value, find the associated name - /// Returns -1 if not found - Index findOptionByCategoryUserValue(UserValue categoryUserValue, const UnownedStringSlice& name) const; - - /// Find a category by case insensitive name. Returns -1 if not found + /// Finds the category by name or -1 if not found + Index findCategoryByName(const UnownedStringSlice& name) const + { + return findTargetIndexByName(LookupKind::Category, name); + } + /// Finds the option index by name or -1 if not found + Index findOptionByName(const UnownedStringSlice& name) const + { + return findTargetIndexByName(LookupKind::Option, name); + } + /// Find the option index of a value, using it's category index and the name + Index findValueByName(Index categoryIndex, const UnownedStringSlice& name) const + { + return findTargetIndexByName(LookupKind(categoryIndex), name); + } + + /// Get the category index from a user value + Index findCategoryByUserValue(UserValue userValue) const + { + return findTargetIndexByUserValue(LookupKind::Category, userValue); + } + /// Can only get options + Index findOptionByUserValue(UserValue userValue) const + { + return findTargetIndexByUserValue(LookupKind::Option, userValue); + } + /// Get a value associated with a category + Index findValueByUserValue(Index categoryIndex, UserValue userValue) const + { + return findTargetIndexByUserValue(LookupKind(categoryIndex), userValue); + } + + /// Given a category user value, find the associated name + /// Returns -1 if not found + Index findOptionByCategoryUserValue(UserValue categoryUserValue, const UnownedStringSlice& name) + const; + + /// Find a category by case insensitive name. Returns -1 if not found Index findCategoryByCaseInsensitiveName(const UnownedStringSlice& slice) const; - - /// Given a category index returns all the options associated. + + /// Given a category index returns all the options associated. ConstArrayView