diff options
Diffstat (limited to 'bindings/cpp')
-rw-r--r-- | bindings/cpp/include/.clang-tidy | 18 | ||||
-rw-r--r-- | bindings/cpp/include/serd/Flags.hpp | 101 | ||||
-rw-r--r-- | bindings/cpp/include/serd/Optional.hpp | 164 | ||||
-rw-r--r-- | bindings/cpp/include/serd/StringView.hpp | 246 | ||||
-rw-r--r-- | bindings/cpp/include/serd/detail/Copyable.hpp | 236 | ||||
-rw-r--r-- | bindings/cpp/include/serd/detail/DynamicWrapper.hpp | 74 | ||||
-rw-r--r-- | bindings/cpp/include/serd/detail/StaticWrapper.hpp | 97 | ||||
-rw-r--r-- | bindings/cpp/include/serd/detail/Wrapper.hpp | 99 | ||||
-rw-r--r-- | bindings/cpp/include/serd/serd.hpp | 2501 | ||||
-rw-r--r-- | bindings/cpp/meson.build | 77 | ||||
-rw-r--r-- | bindings/cpp/test/.clang-tidy | 30 | ||||
-rw-r--r-- | bindings/cpp/test/test_serd_hpp.cpp | 823 |
12 files changed, 4466 insertions, 0 deletions
diff --git a/bindings/cpp/include/.clang-tidy b/bindings/cpp/include/.clang-tidy new file mode 100644 index 00000000..1b176f19 --- /dev/null +++ b/bindings/cpp/include/.clang-tidy @@ -0,0 +1,18 @@ +Checks: > + *, + -*-named-parameter, + -*-non-private-member-variables-in-classes, + -*-uppercase-literal-suffix, + -altera-struct-pack-align, + -cert-dcl50-cpp, + -clang-diagnostic-unused-macros, + -cppcoreguidelines-pro-bounds-pointer-arithmetic, + -fuchsia-default-arguments-declarations, + -fuchsia-multiple-inheritance, + -fuchsia-overloaded-operator, + -llvmlibc-*, + -modernize-use-trailing-return-type, + -readability-implicit-bool-conversion, +WarningsAsErrors: '*' +HeaderFilterRegex: '.*' +FormatStyle: file diff --git a/bindings/cpp/include/serd/Flags.hpp b/bindings/cpp/include/serd/Flags.hpp new file mode 100644 index 00000000..e87bb41d --- /dev/null +++ b/bindings/cpp/include/serd/Flags.hpp @@ -0,0 +1,101 @@ +/* + Copyright 2019-2021 David Robillard <d@drobilla.net> + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted, provided that the above + copyright notice and this permission notice appear in all copies. + + THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +*/ + +#ifndef SERD_FLAGS_HPP +#define SERD_FLAGS_HPP + +#include <type_traits> + +namespace serd { + +/** + @defgroup serdpp_flags Flags + @ingroup serdpp + @{ +*/ + +/** + Type-safe bit flags + + This is a minimal interface for type-safe bit flags, which only allows + values from the corresponding flags enum to be set. It functions like a + normal unsigned integer bit field, but attempting to get or set a flag with + the incorrect type will fail to compile. + + @tparam Flag Strong enumeration type for flag values. +*/ +template<class Flag> +class Flags +{ +public: + static_assert(std::is_enum<Flag>::value, ""); + + using Value = std::make_unsigned_t<std::underlying_type_t<Flag>>; + + /// Construct with no flags set + constexpr Flags() noexcept = default; + + /// Construct from a raw bit field value + constexpr explicit Flags(const Value value) noexcept + : _value{value} + {} + + /// Construct from a single flag + // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) + constexpr Flags(const Flag f) noexcept + : _value{static_cast<Value>(f)} + {} + + /// Set a flag + constexpr Flags operator|(const Flag rhs) const noexcept + { + return Flags{_value | static_cast<Value>(rhs)}; + } + + /// Set all the flags from another set of flags + constexpr Flags operator|(const Flags rhs) const noexcept + { + return Flags{_value | rhs._value}; + } + + /// Return true if only the given flag is set + constexpr bool operator==(const Flag rhs) const noexcept + { + return _value == static_cast<Value>(rhs); + } + + // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) + constexpr operator Value() const noexcept { return _value; } + +private: + Value _value{}; +}; + +/// Make a new Flags by combining two individual flags +template<class Flag> +inline constexpr Flags<Flag> +operator|(const Flag lhs, const Flag rhs) noexcept +{ + return Flags<Flag>{lhs} | rhs; +} + +/** + @} +*/ + +} // namespace serd + +#endif // SERD_FLAGS_HPP diff --git a/bindings/cpp/include/serd/Optional.hpp b/bindings/cpp/include/serd/Optional.hpp new file mode 100644 index 00000000..ee6a7fc2 --- /dev/null +++ b/bindings/cpp/include/serd/Optional.hpp @@ -0,0 +1,164 @@ +/* + Copyright 2019-2021 David Robillard <d@drobilla.net> + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted, provided that the above + copyright notice and this permission notice appear in all copies. + + THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +*/ + +#ifndef SERD_OPTIONAL_HPP +#define SERD_OPTIONAL_HPP + +#include <cassert> +#include <type_traits> +#include <utility> + +namespace serd { + +/** + @defgroup serdpp_optional Optional + @ingroup serdpp + @{ +*/ + +struct ConstructNullOptional {}; + +/// Special tag for constructing an unset Optional +struct Nullopt { + enum class Construct { internal }; + + explicit constexpr Nullopt(Construct) {} +}; + +/** + A simple optional wrapper around a wrapped type with a pointer-like API + + This works like a typical optional type, but only works with Wrapper types, + and exploits the fact that these are interally just pointers to avoid adding + space overhead for an "is_set" flag, like a generic optional class would. + + Types must explicitly opt-in to being optional by providing a constructor + that takes a single ContructNullOptional argument. This constructor should + only be used by the Optional implementation, which guarantees that such an + object will not be used except by calling its cobj() method. +*/ +template<class T> +class Optional +{ +public: + /// The type of the underlying C object + using CType = typename T::CType; + + /// Constructs an empty optional + Optional() = default; + + /// Constructs an empty optional + // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) + Optional(Nullopt) {} + + /// Constructs an optional that contains the given value + // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) + Optional(T value) + : _value{std::move(value)} + {} + + /// Constructs an optional that contains a converted value + template< + typename U, + typename = typename std::enable_if<std::is_convertible<U, T>::value>::type> + // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) + Optional(U&& value) + : _value{std::forward<U>(value)} + {} + + /// Destroys any contained value + void reset() { _value = T{nullptr}; } + + /// Accesses the contained value + const T& operator*() const + { + assert(_value.cobj()); + return _value; + } + + /// Accesses the contained value + T& operator*() + { + assert(_value.cobj()); + return _value; + } + + /// Accesses the contained value + const T* operator->() const + { + assert(_value.cobj()); + return &_value; + } + + /// Accesses the contained value + T* operator->() + { + assert(_value.cobj()); + return &_value; + } + + /// Tests if optional objects are equal + bool operator==(const Optional& optional) + { + return (!*this && !optional) || + (*this && optional && _value == optional._value); + } + + /// Tests if optional objects are not equal + bool operator!=(const Optional& optional) { return !operator==(optional); } + + /// Returns true if this optional contains a value + explicit operator bool() const { return _value.cobj(); } + + /// Returns true if this optional does not contain a value + bool operator!() const { return !_value.cobj(); } + + /// Return a pointer to the underlying C object, or null + CType* cobj() { return _value.cobj(); } + + /// Return a pointer to the underlying C object, or null + const CType* cobj() const { return _value.cobj(); } + +private: + T _value{nullptr}; +}; + +/// Creates an optional object from `value` +template<class T> +constexpr Optional<std::decay_t<T>> +make_optional(T&& value) +{ + return Optional<T>{std::forward<T>(value)}; +} + +/// Creates an optional object with a value constructed in-place from `args` +template<class T, class... Args> +constexpr Optional<T> +make_optional(Args&&... args) +{ + return Optional<T>{std::forward<Args>(args)...}; +} + +/// Constant that represents an empty optional +static constexpr Nullopt nullopt{Nullopt::Construct::internal}; + +/** + @} +*/ + +} // namespace serd + +#endif // SERD_OPTIONAL_HPP diff --git a/bindings/cpp/include/serd/StringView.hpp b/bindings/cpp/include/serd/StringView.hpp new file mode 100644 index 00000000..f62f0827 --- /dev/null +++ b/bindings/cpp/include/serd/StringView.hpp @@ -0,0 +1,246 @@ +/* + Copyright 2019-2021 David Robillard <d@drobilla.net> + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted, provided that the above + copyright notice and this permission notice appear in all copies. + + THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +*/ + +#ifndef SERD_STRINGVIEW_HPP +#define SERD_STRINGVIEW_HPP + +#include "serd/serd.h" + +#include <algorithm> +#include <cstddef> +#include <cstring> +#include <ostream> +#include <stdexcept> +#include <string> + +namespace serd { + +/** + @defgroup serdpp_string_view String View + @ingroup serdpp + @{ +*/ + +/** + Immutable slice of a string. + + This is a minimal implementation that is compatible with std::string_view + and std::string for most basic use cases. This could be replaced with + std::string_view once C++17 support can be relied on. +*/ +class StringView +{ +public: + using char_type = char; + using size_type = size_t; + using traits_type = std::char_traits<char>; + using value_type = char; + using pointer = value_type*; + using const_pointer = const value_type*; + using reference = value_type&; + using const_reference = const value_type&; + using iterator = const char*; + using const_iterator = const char*; + + static constexpr size_type npos = size_t(-1); + + constexpr StringView() noexcept = default; + + constexpr StringView(const char* const str, const size_t len) noexcept + : _str{str} + , _len{len} + {} + + // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) + StringView(const char* const str) noexcept + : _str{str} + , _len{str ? strlen(str) : 0} + {} + + // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) + StringView(const std::string& str) noexcept + : _str{str.c_str()} + , _len{str.length()} + {} + + constexpr size_t size() const { return _len; } + constexpr size_t length() const { return _len; } + constexpr bool empty() const { return _len == 0; } + constexpr const char* c_str() const { return _str; } + constexpr const char* data() const { return _str; } + constexpr const char& front() const { return _str[0]; } + constexpr const char& back() const { return _str[_len - 1]; } + + constexpr const_iterator begin() const { return _str; } + constexpr const_iterator end() const { return _str + _len; } + constexpr const_iterator cbegin() const { return begin(); } + constexpr const_iterator cend() const { return end(); } + + constexpr const char& operator[](const size_t pos) const { return _str[pos]; } + + const char& at(const size_t pos) const + { + if (pos >= size()) { + throw std::out_of_range("serd::StringView::at pos"); + } + + return _str[pos]; + } + + StringView substr(const size_t pos) const + { + if (pos > size()) { + throw std::out_of_range("serd::StringView::substr pos"); + } + + return StringView{data() + pos, size() - pos}; + } + + StringView substr(const size_t pos, const size_t n) const + { + if (pos > size()) { + throw std::out_of_range("serd::StringView::substr pos"); + } + + return StringView{data() + pos, std::min(size() - pos, n)}; + } + + int compare(StringView rhs) const noexcept + { + if (!data() && !rhs.data()) { + return 0; + } + + if (!data()) { + return -1; + } + + if (!rhs.data()) { + return 1; + } + + const size_type len = std::min(size(), rhs.size()); + const int cmp = strncmp(data(), rhs.data(), len); + + if (cmp) { + return cmp; + } + + if (size() == rhs.size()) { + return 0; + } + + if (size() < rhs.size()) { + return -1; + } + + return 1; + } + + template<class Alloc = std::allocator<char>> + std::basic_string<char, traits_type, Alloc> str() const + { + return std::basic_string<char, traits_type, Alloc>(data(), size(), Alloc{}); + } + + template<class Alloc = std::allocator<char>> + std::basic_string<char, traits_type, Alloc> str(const Alloc& alloc) const + { + return std::basic_string<char, traits_type, Alloc>(data(), size(), alloc); + } + + explicit operator std::string() const { return str(); } + + explicit operator const char*() const { return _str; } + + // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) + operator SerdStringView() const { return SerdStringView{_str, _len}; } + +private: + const char* const _str{}; + const size_t _len{}; +}; + +inline bool +operator==(const StringView& lhs, const StringView& rhs) +{ + return !lhs.compare(rhs); +} + +inline bool +operator==(const StringView& lhs, const std::string& rhs) +{ + return lhs.length() == rhs.length() && + !strncmp(lhs.c_str(), rhs.c_str(), lhs.length()); +} + +inline bool +operator==(const StringView& lhs, const char* rhs) +{ + return !strncmp(lhs.c_str(), rhs, lhs.length()); +} + +inline bool +operator!=(const StringView& lhs, const StringView& rhs) +{ + return lhs.compare(rhs); +} + +inline bool +operator!=(const StringView& lhs, const std::string& rhs) +{ + return lhs.length() != rhs.length() || + !!strncmp(lhs.c_str(), rhs.c_str(), lhs.length()); +} + +inline bool +operator!=(const StringView& lhs, const char* rhs) +{ + return !!strncmp(lhs.c_str(), rhs, lhs.length()); +} + +inline bool +operator<(const StringView& lhs, const StringView& rhs) +{ + return lhs.compare(rhs) < 0; +} + +inline bool +operator<(const StringView& lhs, const std::string& rhs) +{ + return lhs.c_str() < StringView(rhs); +} + +inline bool +operator<(const StringView& lhs, const char* rhs) +{ + return strncmp(lhs.c_str(), rhs, lhs.length()) < 0; +} + +inline std::ostream& +operator<<(std::ostream& os, const StringView& str) +{ + os.write(str.data(), std::streamsize(str.size())); + return os; +} + +/** + @} +*/ + +} // namespace serd + +#endif // SERD_STRINGVIEW_HPP diff --git a/bindings/cpp/include/serd/detail/Copyable.hpp b/bindings/cpp/include/serd/detail/Copyable.hpp new file mode 100644 index 00000000..7b1604d7 --- /dev/null +++ b/bindings/cpp/include/serd/detail/Copyable.hpp @@ -0,0 +1,236 @@ +/* + Copyright 2019-2021 David Robillard <d@drobilla.net> + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted, provided that the above + copyright notice and this permission notice appear in all copies. + + THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +*/ + +#ifndef SERD_DETAIL_COPYABLE_HPP +#define SERD_DETAIL_COPYABLE_HPP + +// IWYU pragma: no_include "serd/serd.h" + +#include "serd/detail/DynamicWrapper.hpp" +#include "serd/detail/StaticWrapper.hpp" +#include "serd/detail/Wrapper.hpp" + +#include <cstddef> +#include <memory> +#include <type_traits> +#include <utility> + +namespace serd { +namespace detail { + +/** + @addtogroup serdpp_detail + @{ +*/ + +/// Copy function for a C object +template<class T> +using CopyFunc = T* (*)(const T*); + +template<class T, std::remove_const_t<T>* Copy(SerdAllocator*, const T*)> +typename std::enable_if_t<std::is_const<T>::value, T>* +copy(const T* ptr) +{ + return ptr; // Making a view (const reference), do not copy +} + +template<class T, std::remove_const_t<T>* Copy(SerdAllocator*, const T*)> +typename std::enable_if_t<!std::is_const<T>::value, T>* +copy(const T* ptr) +{ + return ptr ? Copy(nullptr, ptr) : nullptr; // Making a mutable wrapper, copy +} + +/** + Generic wrapper for a "basic" copyable object. + + This wraps objects with simple ownership semantics where a const pointer is + never owned, and a mutable pointer is owned. This has no space overhead + compared to a raw pointer since the ownership is encoded in the type. +*/ +template<class T, + Mutable<T>* Copy(SerdAllocator*, const T*), + bool Equals(const T*, const T*), + void Free(Mutable<T>*)> +class StaticCopyable : public StaticWrapper<T, Free> +{ +public: + using Deleter = StaticDeleter<T, Free>; + using Base = StaticWrapper<T, Free>; + + explicit StaticCopyable(T* ptr) + : Base{ptr} + {} + + StaticCopyable(const StaticCopyable& wrapper) + : Base(copy<T, Copy>(wrapper.cobj())) + {} + + template<class U, void UFree(Mutable<U>*)> + explicit StaticCopyable(const StaticCopyable<U, Copy, Equals, UFree>& wrapper) + : Base(copy<T, Copy>(wrapper.cobj())) + {} + + StaticCopyable(StaticCopyable&&) noexcept = default; + ~StaticCopyable() noexcept = default; + + StaticCopyable& operator=(StaticCopyable&&) noexcept = default; + + StaticCopyable& operator=(const StaticCopyable& wrapper) + { + if (&wrapper != this) { + this->_ptr = std::unique_ptr<T, Deleter>(copy<T, Copy>(wrapper.cobj())); + } + return *this; + } + + template<class U> + bool operator==(const StaticCopyable<U, Copy, Equals, Free>& wrapper) const + { + return Equals(this->cobj(), wrapper.cobj()); + } + + template<class U> + bool operator!=(const StaticCopyable<U, Copy, Equals, Free>& wrapper) const + { + return !operator==(wrapper); + } +}; + +/** + Generic wrapper for a "basic" copyable object. + + This wraps objects with simple ownership semantics where a const pointer is + never owned, and a mutable pointer is owned. This has no space overhead + compared to a raw pointer since the ownership is encoded in the type. +*/ +template<class T, + Mutable<T>* Copy(SerdAllocator*, const T*), + bool Equals(const T*, const T*), + void Free(SerdAllocator*, Mutable<T>*)> +class StaticAllocatedCopyable : public StaticAllocatedWrapper<T, Free> +{ +public: + using Deleter = StaticAllocatedDeleter<T, Free>; + using Base = StaticAllocatedWrapper<T, Free>; + + explicit StaticAllocatedCopyable(T* ptr) + : Base{ptr} + {} + + StaticAllocatedCopyable(const StaticAllocatedCopyable& wrapper) + : Base(copy<T, Copy>(wrapper.cobj())) + {} + + template<class U, void UFree(SerdAllocator*, Mutable<U>*)> + explicit StaticAllocatedCopyable( + const StaticAllocatedCopyable<U, Copy, Equals, UFree>& wrapper) + : Base(copy<T, Copy>(wrapper.cobj())) + {} + + StaticAllocatedCopyable(StaticAllocatedCopyable&&) noexcept = default; + ~StaticAllocatedCopyable() noexcept = default; + + StaticAllocatedCopyable& operator=(StaticAllocatedCopyable&&) noexcept = + default; + + StaticAllocatedCopyable& operator=(const StaticAllocatedCopyable& wrapper) + { + if (&wrapper != this) { + this->_ptr = std::unique_ptr<T, Deleter>(copy<T, Copy>(wrapper.cobj())); + } + return *this; + } + + template<class U> + bool operator==( + const StaticAllocatedCopyable<U, Copy, Equals, Free>& wrapper) const + { + return Equals(this->cobj(), wrapper.cobj()); + } + + template<class U> + bool operator!=( + const StaticAllocatedCopyable<U, Copy, Equals, Free>& wrapper) const + { + return !operator==(wrapper); + } +}; + +/** + Wrapper for a "dynamic" copyable C object. + + This wraps objects that require dynamic tracking of the ownership. +*/ +template<class T, + Mutable<T>* Copy(SerdAllocator*, const T*), + bool Equals(const T*, const T*), + void Free(Mutable<T>*)> +class DynamicCopyable : public Wrapper<T, DynamicDeleter<T, Free>> +{ +public: + using Deleter = DynamicDeleter<T, Free>; + using Base = Wrapper<T, Deleter>; + + explicit DynamicCopyable(std::unique_ptr<T, Deleter> ptr) + : Base{std::move(ptr)} + {} + + DynamicCopyable(const DynamicCopyable& wrapper) + : Base{Copy(nullptr /* FIXME */, wrapper.cobj()), Ownership::owned} + {} + + DynamicCopyable(DynamicCopyable&&) noexcept = default; + DynamicCopyable& operator=(DynamicCopyable&&) noexcept = default; + + ~DynamicCopyable() noexcept = default; + + DynamicCopyable& operator=(const DynamicCopyable& wrapper) + { + if (&wrapper != this) { + this->_ptr = std::unique_ptr<T, Deleter>( + Copy(nullptr /* FIXME */, wrapper.cobj()), Ownership::owned); + } + + return *this; + } + + template<class U> + bool operator==(const DynamicCopyable<U, Copy, Equals, Free>& wrapper) const + { + return Equals(this->cobj(), wrapper.cobj()); + } + + template<class U> + bool operator!=(const DynamicCopyable<U, Copy, Equals, Free>& wrapper) const + { + return !operator==(wrapper); + } + +protected: + explicit DynamicCopyable(std::nullptr_t) + : Base(nullptr) + {} +}; + +/** + @} +*/ + +} // namespace detail +} // namespace serd + +#endif // SERD_DETAIL_COPYABLE_HPP diff --git a/bindings/cpp/include/serd/detail/DynamicWrapper.hpp b/bindings/cpp/include/serd/detail/DynamicWrapper.hpp new file mode 100644 index 00000000..6b3c898a --- /dev/null +++ b/bindings/cpp/include/serd/detail/DynamicWrapper.hpp @@ -0,0 +1,74 @@ +/* + Copyright 2019-2021 David Robillard <d@drobilla.net> + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted, provided that the above + copyright notice and this permission notice appear in all copies. + + THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +*/ + +#ifndef SERD_DETAIL_DYNAMICWRAPPER_HPP +#define SERD_DETAIL_DYNAMICWRAPPER_HPP + +// IWYU pragma: no_include "serd/serd.h" + +#include "serd/detail/Wrapper.hpp" + +#include <type_traits> + +namespace serd { +namespace detail { + +/** + Ownership for `DynamicDeleter`. + + @ingroup serdpp_detail +*/ +enum class Ownership { + owned, ///< This pointer owns the data and must delete it + view, ///< This pointer is just a view and must not delete the data +}; + +/** + Deleter for a C object that can handle dynamic ownership. + + Unlike StaticDeleter, this can be used to handle non-owned references to + mutable objects, at the cost of an extra word for tracking the ownership + (since constness in the type can't convey this information). + + @ingroup serdpp_detail +*/ +template<class T, void Free(Mutable<T>*)> +struct DynamicDeleter { + // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) + DynamicDeleter(const Ownership ownership) + : _ownership{ownership} + {} + + template<class = std::enable_if<!std::is_const<T>::value>> + void operator()(Mutable<T>* const ptr) + { + if (_ownership == Ownership::owned) { + Free(ptr); + } + } + + template<class = std::enable_if<std::is_const<T>::value>> + void operator()(const T*) + {} + +private: + Ownership _ownership; +}; + +} // namespace detail +} // namespace serd + +#endif // SERD_DETAIL_DYNAMICWRAPPER_HPP diff --git a/bindings/cpp/include/serd/detail/StaticWrapper.hpp b/bindings/cpp/include/serd/detail/StaticWrapper.hpp new file mode 100644 index 00000000..9ca82118 --- /dev/null +++ b/bindings/cpp/include/serd/detail/StaticWrapper.hpp @@ -0,0 +1,97 @@ +/* + Copyright 2019-2021 David Robillard <d@drobilla.net> + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted, provided that the above + copyright notice and this permission notice appear in all copies. + + THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +*/ + +#ifndef SERD_DETAIL_STATICWRAPPER_HPP +#define SERD_DETAIL_STATICWRAPPER_HPP + +// IWYU pragma: no_include "serd/serd.h" + +#include "serd/detail/Wrapper.hpp" + +#include <type_traits> + +namespace serd { +namespace detail { + +/** + Simple overhead-free deleter for a C object. + + Can be used with const or mutable pointers, but only mutable pointers will + be freed. In other words, mutability implies ownership, and this can not + handle unowned mutable pointers. + + @ingroup serdpp_detail +*/ +template<class T, void Free(Mutable<T>*)> +struct StaticDeleter { + template<class = std::enable_if<!std::is_const<T>::value>> + void operator()(Mutable<T>* const ptr) + { + Free(ptr); + } + + template<class = std::enable_if<std::is_const<T>::value>> + void operator()(const T*) + {} +}; + +/// Simple overhead-free wrapper for a C object that can free itself +template<class T, void Free(std::remove_const_t<T>*)> +class StaticWrapper : public Wrapper<T, StaticDeleter<T, Free>> +{ +public: + explicit StaticWrapper(T* const ptr) + : Wrapper<T, StaticDeleter<T, Free>>{ptr} + {} +}; + +/** + Simple overhead-free deleter for a C object. + + Can be used with const or mutable pointers, but only mutable pointers will + be freed. In other words, mutability implies ownership, and this can not + handle unowned mutable pointers. + + @ingroup serdpp_detail +*/ +template<class T, void Free(SerdAllocator*, Mutable<T>*)> +struct StaticAllocatedDeleter { + template<class = std::enable_if<!std::is_const<T>::value>> + void operator()(Mutable<T>* const ptr) + { + Free(nullptr, ptr); + } + + template<class = std::enable_if<std::is_const<T>::value>> + void operator()(const T*) + {} +}; + +/// Simple overhead-free wrapper for a C object that uses an allocator +template<class T, void Free(SerdAllocator*, std::remove_const_t<T>*)> +class StaticAllocatedWrapper + : public Wrapper<T, StaticAllocatedDeleter<T, Free>> +{ +public: + explicit StaticAllocatedWrapper(T* const ptr) + : Wrapper<T, StaticAllocatedDeleter<T, Free>>{ptr} + {} +}; + +} // namespace detail +} // namespace serd + +#endif // SERD_DETAIL_STATICWRAPPER_HPP diff --git a/bindings/cpp/include/serd/detail/Wrapper.hpp b/bindings/cpp/include/serd/detail/Wrapper.hpp new file mode 100644 index 00000000..39426775 --- /dev/null +++ b/bindings/cpp/include/serd/detail/Wrapper.hpp @@ -0,0 +1,99 @@ +/* + Copyright 2019-2021 David Robillard <d@drobilla.net> + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted, provided that the above + copyright notice and this permission notice appear in all copies. + + THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +*/ + +#ifndef SERD_DETAIL_WRAPPER_HPP +#define SERD_DETAIL_WRAPPER_HPP + +// IWYU pragma: no_include "serd/serd.h" + +#include <cstddef> +#include <memory> +#include <type_traits> +#include <utility> + +namespace serd { + +/// Utility template for a mutable type which removes const if necessary +template<class T> +class Optional; + +/// Detail namespace +namespace detail { + +/** + @defgroup serdpp_detail Serd C++ API details + Internal C++ wrapper details that should not be used directly by clients. + @ingroup serdpp + @{ +*/ + +/// Utility template for a mutable type which removes const if necessary +template<class T> +using Mutable = typename std::remove_const_t<T>; + +/// Generic C++ wrapper for a C object +template<class T, class Deleter> +class Wrapper +{ +public: + using CType = T; + + explicit Wrapper(T* ptr) + : _ptr{ptr, Deleter{}} + {} + + Wrapper(T* ptr, Deleter deleter) + : _ptr{ptr, std::move(deleter)} + {} + + explicit Wrapper(std::unique_ptr<T, Deleter> ptr) + : _ptr{std::move(ptr)} + {} + + Wrapper(Wrapper&&) noexcept = default; + Wrapper& operator=(Wrapper&&) noexcept = default; + + Wrapper(const Wrapper&) = delete; + Wrapper& operator=(const Wrapper&) = delete; + + ~Wrapper() = default; + + /// Return a pointer to the underlying C object + T* cobj() { return _ptr.get(); } + + /// Return a pointer to the underlying C object + const T* cobj() const { return _ptr.get(); } + +protected: + friend class Optional<T>; + + explicit Wrapper(std::nullptr_t) + : _ptr{nullptr} + {} + + void reset() { _ptr.reset(); } + + std::unique_ptr<T, Deleter> _ptr; +}; + +/** + @} +*/ + +} // namespace detail +} // namespace serd + +#endif // SERD_DETAIL_WRAPPER_HPP diff --git a/bindings/cpp/include/serd/serd.hpp b/bindings/cpp/include/serd/serd.hpp new file mode 100644 index 00000000..28e1621f --- /dev/null +++ b/bindings/cpp/include/serd/serd.hpp @@ -0,0 +1,2501 @@ +/* + Copyright 2019-2021 David Robillard <d@drobilla.net> + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted, provided that the above + copyright notice and this permission notice appear in all copies. + + THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +*/ + +#ifndef SERD_SERD_HPP +#define SERD_SERD_HPP + +#include "serd/Flags.hpp" // IWYU pragma: export +#include "serd/Optional.hpp" // IWYU pragma: export +#include "serd/StringView.hpp" // IWYU pragma: export +#include "serd/detail/Copyable.hpp" // IWYU pragma: export +#include "serd/detail/DynamicWrapper.hpp" // IWYU pragma: export +#include "serd/detail/StaticWrapper.hpp" // IWYU pragma: export +#include "serd/detail/Wrapper.hpp" // IWYU pragma: export + +#include "serd/serd.h" + +#include <cassert> +#include <cstdarg> +#include <cstdint> +#include <cstdio> +#include <functional> +#include <map> +#include <memory> +#include <sstream> +#include <string> +#include <utility> +#include <vector> + +namespace serd { + +/** + @defgroup serdpp Serd C++ API + @{ +*/ + +/** + @defgroup serdpp_status Status Codes + @{ +*/ + +/// @copydoc SerdStatus +enum class Status { + success = SERD_SUCCESS, ///< @copydoc SERD_SUCCESS + failure = SERD_FAILURE, ///< @copydoc SERD_FAILURE + unknown_error = SERD_UNKNOWN_ERROR, ///< @copydoc SERD_UNKNOWN_ERROR + no_data = SERD_NO_DATA, ///< @copydoc SERD_NO_DATA + overflow = SERD_OVERFLOW, ///< @copydoc SERD_OVERFLOW + + bad_alloc = SERD_BAD_ALLOC, ///< @copydoc SERD_BAD_ALLOC + bad_arg = SERD_BAD_ARG, ///< @copydoc SERD_BAD_ARG + bad_call = SERD_BAD_CALL, ///< @copydoc SERD_BAD_CALL + bad_curie = SERD_BAD_CURIE, ///< @copydoc SERD_BAD_CURIE + bad_cursor = SERD_BAD_CURSOR, ///< @copydoc SERD_BAD_CURSOR + bad_event = SERD_BAD_EVENT, ///< @copydoc SERD_BAD_EVENT + bad_index = SERD_BAD_INDEX, ///< @copydoc SERD_BAD_INDEX + bad_label = SERD_BAD_LABEL, ///< @copydoc SERD_BAD_LABEL + bad_literal = SERD_BAD_LITERAL, ///< @copydoc SERD_BAD_LITERAL + bad_pattern = SERD_BAD_PATTERN, ///< @copydoc SERD_BAD_PATTERN + bad_read = SERD_BAD_READ, ///< @copydoc SERD_BAD_READ + bad_stack = SERD_BAD_STACK, ///< @copydoc SERD_BAD_STACK + bad_syntax = SERD_BAD_SYNTAX, ///< @copydoc SERD_BAD_SYNTAX + bad_text = SERD_BAD_TEXT, ///< @copydoc SERD_BAD_TEXT + bad_uri = SERD_BAD_URI, ///< @copydoc SERD_BAD_URI + bad_write = SERD_BAD_WRITE, ///< @copydoc SERD_BAD_WRITE + bad_data = SERD_BAD_DATA, ///< @copydoc SERD_BAD_DATA +}; + +/// @copydoc serd_strerror +inline const char* +strerror(const Status status) +{ + return serd_strerror(static_cast<SerdStatus>(status)); +} + +/** + @} + @defgroup serdpp_string String Utilities + @{ +*/ + +/** + Encode `size` bytes of `buf` into `str`, which must be large enough. + + @param buf Input binary data (vector-like container of bytes). + @return A base64 encoded representation of the data in `buf`. +*/ +template<class Container> +inline std::string +base64_encode(const Container& buf) +{ +#if 0 + const size_t length{serd_base64_encoded_length(buf.size(), wrap_lines)}; + std::string str(length + 1, '\0'); + + serd_base64_encode(&str.at(0), buf.data(), buf.size(), wrap_lines); + return str; +#endif + + (void)buf; + return ""; // FIXME +} + +// FIXME +#if 0 +/** + Decode a base64 string. + + Container must be a vector-like container of bytes. + + @param str Base64 string to decode. + @return The decoded data represented in `str`. +*/ +template<class Container = std::vector<uint8_t>> +inline Container +base64_decode(StringView str) +{ +# if 0 + size_t size{serd_base64_decoded_size(str.length())}; + Container buf(size, 0); + + serd_base64_decode(&buf.at(0), &size, str.c_str(), str.length()); + buf.resize(size); + return buf; +# endif + (void)str; + return {}; // FIXME +} +#endif + +// TODO: serd_canonical_path + +// TODO: grouping? +static inline size_t +stream_write(const void* buf, size_t size, size_t nmemb, void* sink) noexcept +{ + (void)size; + assert(size == 1); + + std::ostream& os = *static_cast<std::ostream*>(sink); + + try { + os.write(static_cast<const char*>(buf), std::streamsize(nmemb)); + return os.good() ? nmemb : 0u; + } catch (...) { + } + return 0; +} + +/** + @} + @defgroup serdpp_syntax Syntax Utilities + @{ +*/ + +/// @copydoc SerdSyntax +enum class Syntax { + empty = SERD_SYNTAX_EMPTY, ///< @copydoc SERD_SYNTAX_EMPTY + Turtle = SERD_TURTLE, ///< @copydoc SERD_TURTLE + NTriples = SERD_NTRIPLES, ///< @copydoc SERD_NTRIPLES + NQuads = SERD_NQUADS, ///< @copydoc SERD_NQUADS + TriG = SERD_TRIG ///< @copydoc SERD_TRIG +}; + +/// @copydoc serd_syntax_by_name +inline Syntax +syntax_by_name(StringView name) +{ + return Syntax(serd_syntax_by_name(name.c_str())); +} + +/// @copydoc serd_guess_syntax +inline Syntax +guess_syntax(StringView filename) +{ + return Syntax(serd_guess_syntax(filename.c_str())); +} + +/** + Return whether a syntax can represent multiple graphs. + + @return True for @ref Syntax::NQuads and @ref Syntax::TriG, false otherwise. +*/ +inline bool +syntax_has_graphs(const Syntax syntax) +{ + return serd_syntax_has_graphs(static_cast<SerdSyntax>(syntax)); +} + +/** + @} + @defgroup serdpp_data Data + @{ + @defgroup serdpp_uri URI + @{ +*/ + +/** + Get the unescaped path and hostname from a file URI. + + The returned path and `*hostname` must be freed with serd_free(). + + @param uri A file URI. + @param hostname If non-null, set to the hostname, if present. + @return A filesystem path. +*/ +inline std::string +parse_file_uri(StringView uri, std::string* hostname = nullptr) +{ + char* c_hostname = nullptr; + char* c_path = serd_parse_file_uri(nullptr, uri.data(), &c_hostname); + if (hostname && c_hostname) { + *hostname = c_hostname; + } + + std::string path{c_path}; + serd_free(nullptr, c_hostname); + serd_free(nullptr, c_path); + return path; +} + +/// @copydoc serd_uri_string_has_scheme +inline bool +uri_string_has_scheme(StringView string) +{ + return serd_uri_string_has_scheme(string.c_str()); +} + +/** + A parsed URI. + + This directly refers to slices in other strings, it does not own any memory + itself. Thus, URIs can be parsed and/or resolved against a base URI + in-place without allocating memory. +*/ +class URI +{ +public: + /** + Component of a URI. + + Note that there is a distinction between a component being non-present + and present but empty. For example, "file:///path" has an empty + authority, while "file:/path" has no authority. A non-present component + has its `data()` pointer set to null, while an empty component has a + data pointer, but length zero. + */ + using Component = StringView; + + /// Construct a URI by parsing a URI string + explicit URI(StringView str) + : _uri{serd_parse_uri(str.data())} + {} + + /// Construct a URI from a C URI view + explicit URI(const SerdURIView& uri) + : _uri{uri} + {} + + /// Return the scheme of this URI + Component scheme() const { return make_component(_uri.scheme); } + + /// Return the authority of this URI + Component authority() const { return make_component(_uri.authority); } + + /// Return the path prefix of this URI, which is set if it has been resolved + Component path_prefix() const { return make_component(_uri.path_prefix); } + + /// Return the path (suffix) of this URI + Component path() const { return make_component(_uri.path); } + + /// Return the query + Component query() const { return make_component(_uri.query); } + + /// Return the fragment of this URI + Component fragment() const { return make_component(_uri.fragment); } + + /// Return this URI resolved against `base` + URI resolve(const URI& base) const + { + return URI{serd_resolve_uri(_uri, base._uri)}; + } + + /// Return URI as a string + std::string string() const + { + std::ostringstream ss; + + serd_write_uri(_uri, stream_write, &ss); + return ss.str(); + } + + /// Return this URI as a string relative to `base` + std::string relative_string(const URI& base) const + { + std::ostringstream ss; + + const SerdURIView rel = serd_relative_uri(_uri, base._uri); + + serd_write_uri(rel, stream_write, &ss); + return ss.str(); + } + + /** + Return this URI as a string relative to `base` but constrained to `root`. + + The returned URI string is relative iff this URI is a child of both `base` + and `root`. The `root` must be a prefix of `base` and can be used keep + up-references ("../") within a certain namespace. + */ + std::string relative_string(const URI& base, const URI& root) const + { + if (serd_uri_is_within(_uri, root._uri)) { + return relative_string(base); + } + + return string(); + } + + /// Return a pointer to the underlying C object + const SerdURIView* cobj() const { return &_uri; } + +private: + static Component make_component(const SerdStringView slice) + { + return slice.buf ? Component{slice.buf, slice.len} : Component{}; + } + + SerdURIView _uri; +}; + +inline std::ostream& +operator<<(std::ostream& os, const URI& uri) +{ + serd_write_uri(*uri.cobj(), stream_write, &os); + return os; +} + +/** + @} + @defgroup serdpp_node Node + @{ +*/ + +/// @copydoc SerdNodeType +enum class NodeType { + literal = SERD_LITERAL, ///< @copydoc SERD_LITERAL + URI = SERD_URI, ///< @copydoc SERD_URI + blank = SERD_BLANK, ///< @copydoc SERD_BLANK + variable = SERD_VARIABLE, ///< @copydoc SERD_VARIABLE +}; + +/// @copydoc SerdNodeFlag +enum class NodeFlag { + is_long = SERD_IS_LONG, ///< @copydoc SERD_IS_LONG + has_datatype = SERD_HAS_DATATYPE, ///< @copydoc SERD_HAS_DATATYPE + has_language = SERD_HAS_LANGUAGE, ///< @copydoc SERD_HAS_LANGUAGE +}; + +/// Bitwise OR of NodeFlag values +using NodeFlags = Flags<NodeFlag>; + +template<class CObj> +using NodeHandle = detail::StaticAllocatedCopyable<CObj, + serd_node_copy, + serd_node_equals, + serd_node_free>; + +// template<class CObj> +// class NodeWrapper; + +/// A view of an immutable node +// using NodeView = NodeWrapper<const SerdNode>; +class NodeView; + +/// Common base class for any wrapped node +template<class CObj> +class NodeWrapper : public NodeHandle<CObj> +{ +public: + template<class C> + // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) + NodeWrapper(const NodeWrapper<C>& node) + : NodeHandle<CObj>{node} + {} + + /// @copydoc serd_node_type + NodeType type() const { return NodeType(serd_node_type(this->cobj())); } + + /// @copydoc serd_node_string + const char* c_str() const { return serd_node_string(this->cobj()); } + + /// @copydoc serd_node_string + StringView str() const { return StringView{c_str(), length()}; } + + /// @copydoc serd_node_length + size_t size() const { return serd_node_length(this->cobj()); } + + /// @copydoc serd_node_length + size_t length() const { return serd_node_length(this->cobj()); } + + /// @copydoc serd_node_datatype + Optional<NodeView> datatype() const; + + /// @copydoc serd_node_language + Optional<NodeView> language() const; + + /// @copydoc serd_node_string_view + StringView string_view() const { return StringView{c_str(), length()}; } + + /// @copydoc serd_node_uri_view + SerdURIView uri_view() const { return serd_node_uri_view(this->cobj()); } + + /// Returns a newly allocated copy of the node's string + explicit operator std::string() const + { + return std::string{c_str(), length()}; + } + + // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) + explicit operator StringView() const { return StringView(c_str(), length()); } + + // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) + explicit operator SerdStringView() const + { + return SerdStringView{c_str(), length()}; + } + + /// Return a pointer to the first character in the node's string + const char* begin() const { return c_str(); } + + /// Return a pointer to the null terminator at the end of the node's string + const char* end() const { return c_str() + length(); } + + /// Return true if the node's string is empty + bool empty() const { return length() == 0; } + +protected: + explicit NodeWrapper(CObj* const ptr) + : NodeHandle<CObj>{ptr} + {} +}; + +/// A non-owning constant view of some other node +class NodeView : public NodeWrapper<const SerdNode> +{ +public: + /// Create a view of a C node pointer + // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) + NodeView(const SerdNode* const ptr) + : NodeWrapper{ptr} + {} + + /// Create a view of some other node + template<class C> + // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) + NodeView(const NodeWrapper<C>& node) + : NodeWrapper{node} + {} +}; + +/// @copydoc serd_node_datatype +template<class CObj> +inline Optional<NodeView> +NodeWrapper<CObj>::datatype() const +{ + return NodeView{serd_node_datatype(this->cobj())}; +} + +/// @copydoc serd_node_language +template<class CObj> +inline Optional<NodeView> +NodeWrapper<CObj>::language() const +{ + return NodeView{serd_node_language(this->cobj())}; +} + +/** + Compare two nodes. + + Nodes are ordered first by type, then by string value, then by language or + datatype, if present. +*/ +inline bool +operator<(const NodeView& lhs, const NodeView& rhs) +{ + return serd_node_compare(lhs.cobj(), rhs.cobj()) < 0; +} + +/// An RDF node +class Node : public NodeWrapper<SerdNode> +{ +public: + /// Create a node by taking ownership of a C node + explicit Node(SerdNode* const node) + : NodeWrapper<SerdNode>{node} + {} + + /// Create a node by copying another node + // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) + Node(const NodeView& node) + : NodeWrapper<SerdNode>{node} + {} + + explicit Node(const SerdValue& value) + : NodeWrapper{serd_new_value(nullptr, value)} + {} + + /// Create an xsd:boolean node from a ``bool`` + explicit Node(const bool b) + : NodeWrapper{serd_new_value(nullptr, serd_bool(b))} + {} + + /// Create an xsd:double node from a ``double`` + explicit Node(const double d) + : NodeWrapper{serd_new_value(nullptr, serd_double(d))} + {} + + /// Create an xsd:float node from a ``float`` + explicit Node(const float f) + : NodeWrapper{serd_new_value(nullptr, serd_float(f))} + {} + + /// Create an xsd:long node from a ``int64_t`` + explicit Node(const int64_t i) + : NodeWrapper{serd_new_value(nullptr, serd_long(i))} + {} + + /// Create an xsd:int node from a ``int32_t`` + explicit Node(const int32_t i) + : NodeWrapper{serd_new_value(nullptr, serd_int(i))} + {} + + /// Create an xsd:short node from a ``int16_t`` + explicit Node(const int16_t i) + : NodeWrapper{serd_new_value(nullptr, serd_short(i))} + {} + + /// Create an xsd:byte node from a ``int8_t`` + explicit Node(const int8_t i) + : NodeWrapper{serd_new_value(nullptr, serd_byte(i))} + {} + + /// Create an xsd:unsignedLong node from a ``int64_t`` + explicit Node(const uint64_t i) + : NodeWrapper{serd_new_value(nullptr, serd_ulong(i))} + {} + + /// Create an xsd:unsignedInt node from a ``int32_t`` + explicit Node(const uint32_t i) + : NodeWrapper{serd_new_value(nullptr, serd_uint(i))} + {} + + /// Create an xsd:unsignedShort node from a ``int16_t`` + explicit Node(const uint16_t i) + : NodeWrapper{serd_new_value(nullptr, serd_ushort(i))} + {} + + /// Create an xsd:unsignedByte node from a ``int8_t`` + explicit Node(const uint8_t i) + : NodeWrapper{serd_new_value(nullptr, serd_ubyte(i))} + {} + + Node(const Node& node) = default; + Node& operator=(const Node& node) = default; + + Node(Node&& node) = default; + Node& operator=(Node&& node) = default; + + ~Node() = default; + +private: + friend class Optional<Node>; + friend class Caret; + + explicit Node(std::nullptr_t) + : NodeWrapper{nullptr} + {} +}; + +inline std::ostream& +operator<<(std::ostream& os, const NodeView& node) +{ + return os << node.c_str(); +} + +/// Create a new simple "token" node +inline Node +make_token(const NodeType type, StringView str) +{ + return Node{serd_new_token(nullptr, static_cast<SerdNodeType>(type), str)}; +} + +/// Create a new plain literal node with no language from `str` +inline Node +make_string(StringView str) +{ + return Node{serd_new_string(nullptr, str)}; +} + +/// @copydoc serd_new_uri +inline Node +make_uri(StringView uri) +{ + return Node{serd_new_uri(nullptr, uri)}; +} + +/// @copydoc serd_new_parsed_uri +inline Node +make_uri(SerdURIView uri) +{ + return Node{serd_new_parsed_uri(nullptr, uri)}; +} + +/// @copydoc serd_new_parsed_uri +inline Node +make_uri(URI uri) +{ + return Node{serd_new_parsed_uri(nullptr, *uri.cobj())}; +} + +/// Create a new file URI node from a local filesystem path +inline Node +make_file_uri(StringView path) +{ + return Node{serd_new_file_uri(nullptr, path, SERD_EMPTY_STRING())}; +} + +/// Create a new file URI node from a filesystem path on some host +inline Node +make_file_uri(StringView path, StringView hostname) +{ + return Node{serd_new_file_uri(nullptr, path, hostname)}; +} + +/// @copydoc serd_new_literal +inline Node +make_literal(StringView string, NodeFlags flags, StringView meta) +{ + return Node{ + serd_new_literal(nullptr, string, static_cast<SerdNodeFlags>(flags), meta)}; +} + +/// Create a new blank node from a local name +inline Node +make_blank(StringView str) +{ + return Node{serd_new_token(nullptr, SERD_BLANK, str)}; +} + +/// Create a new plain literal with an optional language tag +inline Node +make_plain_literal(StringView str, StringView lang) +{ + return Node{serd_new_literal(nullptr, str, SERD_HAS_LANGUAGE, lang)}; +} + +/// Create a new typed literal node from `str` +inline Node +make_typed_literal(StringView str, const StringView datatype) +{ + return Node{serd_new_literal(nullptr, str, SERD_HAS_DATATYPE, datatype)}; +} + +template<class T> +inline SerdValue +value(const T value); + +template<> +inline SerdValue +value(const bool value) +{ + return serd_bool(value); +} + +template<> +inline SerdValue +value(const double value) +{ + return serd_double(value); +} + +template<> +inline SerdValue +value(const float value) +{ + return serd_float(value); +} + +template<> +inline SerdValue +value(const int64_t value) +{ + return serd_long(value); +} + +template<> +inline SerdValue +value(const int32_t value) +{ + return serd_int(value); +} + +template<> +inline SerdValue +value(const int16_t value) +{ + return serd_short(value); +} + +template<> +inline SerdValue +value(const int8_t value) +{ + return serd_byte(value); +} + +template<> +inline SerdValue +value(const uint64_t value) +{ + return serd_ulong(value); +} + +template<> +inline SerdValue +value(const uint32_t value) +{ + return serd_uint(value); +} + +template<> +inline SerdValue +value(const uint16_t value) +{ + return serd_ushort(value); +} + +template<> +inline SerdValue +value(const uint8_t value) +{ + return serd_ubyte(value); +} + +template<class T> +inline Node +make(const T v) +{ + return Node{value(v)}; +} + +/// @copydoc serd_new_decimal +inline Node +make_decimal(double d) +{ + return Node{serd_new_decimal(nullptr, d)}; +} + +/// @copydoc serd_new_integer +inline Node +make_integer(int64_t i) +{ + return Node{serd_new_integer(nullptr, i)}; +} + +/** + Create a new canonical xsd:base64Binary literal. + + This function can be used to make a node out of arbitrary binary data, which + can be decoded using base64_decode(). + + @param buf Raw binary data to encode in node. + @param size Size of `buf` in bytes. +*/ +inline Node +make_base64(const void* buf, size_t size) +{ + return Node{serd_new_base64(nullptr, buf, size)}; +} + +/// Prototype for Node get() templates +template<class T> +inline T +get(NodeView node); + +/// @copydoc serd_get_boolean +template<> +inline bool +get<bool>(NodeView node) +{ + return serd_get_value_as(node.cobj(), SERD_BOOL, true).data.as_bool; +} + +/// @copydoc serd_get_double +template<> +inline double +get<double>(NodeView node) +{ + return serd_get_value_as(node.cobj(), SERD_DOUBLE, true).data.as_double; +} + +/// @copydoc serd_get_float +template<> +inline float +get<float>(NodeView node) +{ + return serd_get_value_as(node.cobj(), SERD_FLOAT, true).data.as_float; +} + +/// @copydoc serd_get_long +template<> +inline int64_t +get<int64_t>(NodeView node) +{ + return serd_get_value_as(node.cobj(), SERD_LONG, true).data.as_long; +} + +/// @copydoc serd_get_ulong +template<> +inline uint64_t +get<uint64_t>(NodeView node) +{ + return serd_get_value_as(node.cobj(), SERD_ULONG, true).data.as_ulong; +} + +/** + @} + @defgroup serdpp_nodes Nodes + @{ +*/ + +// TODO + +/** + @} + @defgroup serdpp_caret Caret + @{ +*/ + +/// Caret handle +template<class CObj> +using CaretHandle = detail::StaticAllocatedCopyable<CObj, + serd_caret_copy, + serd_caret_equals, + serd_caret_free>; + +/// Caret wrapper +template<class CObj> +class CaretWrapper : public CaretHandle<CObj> +{ +public: + explicit CaretWrapper(CObj* caret) + : CaretHandle<CObj>{caret} + {} + + template<class C> + // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) + CaretWrapper(const CaretWrapper<C>& caret) + : CaretHandle<CObj>{caret.cobj()} + {} + + /// @copydoc serd_caret_name + NodeView name() const { return NodeView(serd_caret_name(this->cobj())); } + + /// @copydoc serd_caret_line + unsigned line() const { return serd_caret_line(this->cobj()); } + + /// @copydoc serd_caret_column + unsigned column() const { return serd_caret_column(this->cobj()); } +}; + +/// Caret view +using CaretView = CaretWrapper<const SerdCaret>; + +/// Extra data managed by mutable (user created) Caret +struct CaretData { + Node name_node; +}; + +/// @copydoc SerdCaret +class Caret + : private CaretData + , public CaretWrapper<SerdCaret> +{ +public: + /** + Create a new caret. + + @param name The name of the document or stream (usually a file URI) + @param line The line number in the document (1-based) + @param col The column number in the document (1-based) + */ + Caret(const NodeView& name, const unsigned line, const unsigned col) + : CaretData{Node{name}} + , CaretWrapper{serd_caret_new(nullptr, name_node.cobj(), line, col)} + {} + + // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) + Caret(const CaretView& caret) + : Caret(caret.name(), caret.line(), caret.column()) + {} + +private: + friend class Optional<Caret>; + friend class Statement; + + explicit Caret(std::nullptr_t) + : CaretData{Node{nullptr}} + , CaretWrapper{nullptr} + {} +}; + +/** + @} + @defgroup serdpp_statement Statement + @{ +*/ + +/// @copydoc SerdField +enum class Field { + subject = SERD_SUBJECT, ///< @copydoc SERD_SUBJECT + predicate = SERD_PREDICATE, ///< @copydoc SERD_PREDICATE + object = SERD_OBJECT, ///< @copydoc SERD_OBJECT + graph = SERD_GRAPH ///< @copydoc SERD_GRAPH +}; + +template<class CObj> +using StatementHandle = detail::StaticAllocatedCopyable<CObj, + serd_statement_copy, + serd_statement_equals, + serd_statement_free>; + +template<class CObj> +class StatementWrapper; + +/// View of a constant statement +using StatementView = StatementWrapper<const SerdStatement>; + +/// Extra data managed by mutable (user created) Statement +struct StatementData { + Node _subject; + Node _predicate; + Node _object; + Optional<Node> _graph; + Optional<Caret> _caret; +}; + +/// Statement wrapper +template<class CObj> +class StatementWrapper : public StatementHandle<CObj> +{ +public: + explicit StatementWrapper(CObj* statement) + : StatementHandle<CObj>{statement} + {} + + template<class C> + // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) + StatementWrapper(const StatementWrapper<C>& statement) + : StatementHandle<CObj>{statement} + {} + + /// @copydoc serd_statement_node + NodeView node(Field field) const + { + return NodeView{ + serd_statement_node(this->cobj(), static_cast<SerdField>(field))}; + } + + /// @copydoc serd_statement_subject + NodeView subject() const + { + return NodeView{serd_statement_subject(this->cobj())}; + } + + /// @copydoc serd_statement_predicate + NodeView predicate() const + { + return NodeView{serd_statement_predicate(this->cobj())}; + } + + /// @copydoc serd_statement_object + NodeView object() const + { + return NodeView{serd_statement_object(this->cobj())}; + } + + /// @copydoc serd_statement_graph + Optional<NodeView> graph() const + { + return NodeView{serd_statement_graph(this->cobj())}; + } + + /// @copydoc serd_statement_caret + Optional<CaretView> caret() const + { + return CaretView{serd_statement_caret(this->cobj())}; + } + + /// @copydoc serd_statement_matches + bool matches(Optional<NodeView> subject, + Optional<NodeView> predicate, + Optional<NodeView> object, + Optional<NodeView> graph = {}) const + { + return serd_statement_matches(this->cobj(), + subject.cobj(), + predicate.cobj(), + object.cobj(), + graph.cobj()); + } + +private: + template<class CIter> + friend class CursorWrapper; + + StatementWrapper() + : StatementHandle<CObj>{nullptr} + {} +}; + +/// @copydoc SerdStatement +class Statement + : public StatementData + , public StatementWrapper<SerdStatement> +{ +public: + Statement(const NodeView& s, + const NodeView& p, + const NodeView& o, + const NodeView& g, + Optional<CaretView> caret = {}) + : StatementData{s, p, o, g, caret ? *caret : Optional<Caret>{}} + , StatementWrapper{serd_statement_new(nullptr, + _subject.cobj(), + _predicate.cobj(), + _object.cobj(), + _graph.cobj(), + _caret.cobj())} + {} + + Statement(const NodeView& s, + const NodeView& p, + const NodeView& o, + Optional<CaretView> caret = {}) + : StatementData{s, p, o, {}, caret ? *caret : Optional<Caret>{}} + , StatementWrapper{serd_statement_new(nullptr, + _subject.cobj(), + _predicate.cobj(), + _object.cobj(), + nullptr, + _caret.cobj())} + {} + + // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) + Statement(const StatementView& statement) + : StatementData{statement.subject(), + statement.predicate(), + statement.object(), + statement.graph() ? *statement.graph() : Optional<Node>{}, + statement.caret() ? *statement.caret() : Optional<Caret>{}} + , StatementWrapper{statement} + {} +}; + +/** + @} + @} + @defgroup serdpp_world World + @{ +*/ + +/// @copydoc SerdLogLevel +enum class LogLevel { + emergency = SERD_LOG_LEVEL_EMERGENCY, ///< @copydoc SERD_LOG_LEVEL_EMERGENCY + alert = SERD_LOG_LEVEL_ALERT, ///< @copydoc SERD_LOG_LEVEL_ALERT + critical = SERD_LOG_LEVEL_CRITICAL, ///< @copydoc SERD_LOG_LEVEL_CRITICAL + error = SERD_LOG_LEVEL_ERROR, ///< @copydoc SERD_LOG_LEVEL_ERROR + warning = SERD_LOG_LEVEL_WARNING, ///< @copydoc SERD_LOG_LEVEL_WARNING + notice = SERD_LOG_LEVEL_NOTICE, ///< @copydoc SERD_LOG_LEVEL_NOTICE + info = SERD_LOG_LEVEL_INFO, ///< @copydoc SERD_LOG_LEVEL_INFO + debug = SERD_LOG_LEVEL_DEBUG ///< @copydoc SERD_LOG_LEVEL_DEBUG +}; + +/// Extended fields for a log message +using LogFields = std::map<StringView, StringView>; + +/// User-provided callback function for handling a log message +using LogFunc = std::function<Status(LogLevel, LogFields, std::string&&)>; + +/// @copydoc SerdWorld +class World : public detail::StaticWrapper<SerdWorld, serd_world_free> +{ +public: + World() + : StaticWrapper{serd_world_new(nullptr)} + {} + + NodeView get_blank() { return NodeView(serd_world_get_blank(cobj())); } + + void set_message_func(LogFunc log_func) + { + _log_func = std::move(log_func); + serd_set_log_func(cobj(), s_log_func, this); + } + + SERD_LOG_FUNC(4, 5) + Status log(const LogLevel level, + const LogFields& fields, + const char* const fmt, + ...) + { + va_list args; + va_start(args, fmt); + + std::vector<SerdLogField> c_fields(fields.size()); + size_t index = 0; + for (const auto& f : fields) { + c_fields[index].key = f.first.c_str(); + c_fields[index].value = f.second.c_str(); + ++index; + } + + const SerdStatus st = serd_vxlogf(cobj(), + static_cast<SerdLogLevel>(level), + fields.size(), + c_fields.data(), + fmt, + args); + + va_end(args); + return static_cast<Status>(st); + } + +private: + SERD_LOG_FUNC(1, 0) + static std::string format(const char* fmt, va_list args) noexcept + { + va_list args_copy; + va_copy(args_copy, args); + + const auto n_bytes = + static_cast<unsigned>(vsnprintf(nullptr, 0, fmt, args_copy)); + + va_end(args_copy); + +#if __cplusplus >= 201703L + std::string result(n_bytes, '\0'); + vsnprintf(result.data(), n_bytes + 1u, fmt, args); +#else + std::vector<char> str(n_bytes + 1u, '\0'); + vsnprintf(str.data(), n_bytes + 1u, fmt, args); + std::string result(str.data(), size_t(n_bytes)); +#endif + return result; + } + + static SerdStatus s_log_func(void* handle, + const SerdLogLevel level, + const size_t n_fields, + const SerdLogField* const fields, + const SerdStringView message) noexcept + { + const auto* const self = static_cast<const World*>(handle); + try { + LogFields cpp_fields; + for (size_t i = 0; i < n_fields; ++i) { + cpp_fields.emplace(fields[i].key, fields[i].value); + } + + return static_cast<SerdStatus>( + self->_log_func(static_cast<LogLevel>(level), + cpp_fields, + std::string(message.buf, message.len))); + } catch (...) { + return SERD_UNKNOWN_ERROR; + } + } + + LogFunc _log_func{}; +}; + +/** + @} + @defgroup serdpp_streaming Data Streaming + @{ +*/ + +/** + @defgroup serdpp_event Events + @{ +*/ + +// TODO + +/// @copydoc SerdStatementFlag +enum class StatementFlag { + empty_S = SERD_EMPTY_S, ///< @copydoc SERD_EMPTY_S + anon_S = SERD_ANON_S, ///< @copydoc SERD_ANON_S + anon_O = SERD_ANON_O, ///< @copydoc SERD_ANON_O + list_S = SERD_LIST_S, ///< @copydoc SERD_LIST_S + list_O = SERD_LIST_O, ///< @copydoc SERD_LIST_O + terse_S = SERD_TERSE_S, ///< @copydoc SERD_TERSE_S + terse_O = SERD_TERSE_O ///< @copydoc SERD_TERSE_O +}; + +/// Bitwise OR of StatementFlag values +using StatementFlags = Flags<StatementFlag>; + +/// @copydoc SerdEventType +enum class EventType { + base = SERD_BASE, ///< @copydoc SERD_BASE + prefix = SERD_PREFIX, ///< @copydoc SERD_PREFIX + statement = SERD_STATEMENT, ///< @copydoc SERD_STATEMENT + end = SERD_END ///< @copydoc SERD_END +}; + +struct BaseEvent { + NodeView uri; ///< Base URI +}; + +struct PrefixEvent { + NodeView name; ///< Prefix name + NodeView uri; ///< Namespace URI +}; + +struct StatementEvent { + StatementFlags flags; ///< Flags for pretty-printing + StatementView statement; ///< Statement +}; + +struct EndEvent { + NodeView node; ///< Anonymous node that is finished +}; + +class Event +{ +public: + explicit Event(const SerdEvent* const e) + : _event{*e} + {} + + EventType type() const { return static_cast<EventType>(_event.type); } + + BaseEvent base() const + { + assert(_event.type == SERD_BASE); + return {NodeView{_event.base.uri}}; + } + + PrefixEvent prefix() const + { + assert(_event.type == SERD_PREFIX); + return {NodeView{_event.prefix.name}, NodeView{_event.prefix.uri}}; + } + + StatementEvent statement() const + { + assert(_event.type == SERD_STATEMENT); + return {StatementFlags{_event.statement.flags}, + StatementView{_event.statement.statement}}; + } + + EndEvent end() const + { + assert(_event.type == SERD_END); + return {NodeView{_event.end.node}}; + } + +private: + SerdEvent _event; + + // union { + // BaseEvent base; + // PrefixEvent prefix; + // StatementEvent statement; + // EndEvent end; + // } event; +}; + +/** + @} + @defgroup serdpp_sink Sink + @{ +*/ + +// FIXME: Document +using BaseFunc = std::function<Status(NodeView)>; +using PrefixFunc = std::function<Status(NodeView name, NodeView uri)>; +using StatementFunc = std::function<Status(StatementFlags, StatementView)>; +using EndFunc = std::function<Status(NodeView)>; + +/// Common base class for any wrapped sink +template<class CSink> +class SinkWrapper : public detail::StaticWrapper<CSink, serd_sink_free> +{ +public: + /// @copydoc serd_sink_write_base + Status base(const NodeView& uri) const + { + return Status(serd_sink_write_base(this->cobj(), uri.cobj())); + } + + /// @copydoc serd_sink_write_prefix + Status prefix(NodeView name, const NodeView& uri) const + { + return Status( + serd_sink_write_prefix(this->cobj(), name.cobj(), uri.cobj())); + } + + /// @copydoc serd_sink_write_statement + Status statement(StatementFlags flags, StatementView statement) const + { + return Status( + serd_sink_write_statement(this->cobj(), flags, statement.cobj())); + } + + /// @copydoc serd_sink_write + Status write(StatementFlags flags, + const NodeView& subject, + const NodeView& predicate, + const NodeView& object, + Optional<NodeView> graph = {}) const + { + return Status(serd_sink_write(this->cobj(), + flags, + subject.cobj(), + predicate.cobj(), + object.cobj(), + graph.cobj())); + } + + /// @copydoc serd_sink_write_end + Status end(const NodeView& node) const + { + return Status(serd_sink_write_end(this->cobj(), node.cobj())); + } + +protected: + explicit SinkWrapper(CSink* const ptr) + : detail::StaticWrapper<CSink, serd_sink_free>{ptr} + {} +}; + +/// A non-owning constant view of some other sink +class SinkView final : public SinkWrapper<const SerdSink> +{ +public: + /// Create a view of a C sink + explicit SinkView(const SerdSink* const ptr) + : SinkWrapper<const SerdSink>{ptr} + {} + + /// Create a view of some other sink + // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) + SinkView(const SinkWrapper<SerdSink>& sink) + : SinkWrapper<const SerdSink>{sink.cobj()} + {} +}; + +/// @copydoc SerdSink +class Sink final : public SinkWrapper<SerdSink> +{ +public: + explicit Sink(const World& world) + : SinkWrapper{serd_sink_new(world.cobj(), this, s_event, nullptr)} + {} + + explicit Sink(SerdSink* const ptr) + : SinkWrapper{ptr} + {} + + /// Set a function to be called when the base URI changes + void set_base_func(BaseFunc base_func) { _base_func = std::move(base_func); } + + /// Set a function to be called when a namespace prefix changes + void set_prefix_func(PrefixFunc prefix_func) + { + _prefix_func = std::move(prefix_func); + } + + /// Set a function to be called for every statement + void set_statement_func(StatementFunc statement_func) + { + _statement_func = std::move(statement_func); + } + + /// Set a function to be called at the end of an anonymous node + void set_end_func(EndFunc end_func) { _end_func = std::move(end_func); } + +private: + static SerdStatus s_base(void* handle, const SerdNode* uri) noexcept + { + const auto* const sink = static_cast<const Sink*>(handle); + return sink->_base_func ? SerdStatus(sink->_base_func(NodeView(uri))) + : SERD_SUCCESS; + } + + static SerdStatus s_prefix(void* handle, + const SerdNode* name, + const SerdNode* uri) noexcept + { + const auto* const sink = static_cast<const Sink*>(handle); + return sink->_prefix_func + ? SerdStatus(sink->_prefix_func(NodeView(name), NodeView(uri))) + : SERD_SUCCESS; + } + + static SerdStatus s_statement(void* handle, + SerdStatementFlags flags, + const SerdStatement* statement) noexcept + { + const auto* const sink = static_cast<const Sink*>(handle); + return sink->_statement_func + ? SerdStatus(sink->_statement_func(StatementFlags(flags), + StatementView(statement))) + : SERD_SUCCESS; + } + + static SerdStatus s_end(void* handle, const SerdNode* node) noexcept + { + const auto* const sink = static_cast<const Sink*>(handle); + return sink->_end_func ? SerdStatus(sink->_end_func(NodeView(node))) + : SERD_SUCCESS; + } + + static SerdStatus s_event(void* handle, const SerdEvent* event) noexcept + { + const auto* const sink = static_cast<const Sink*>(handle); + + switch (event->type) { + case SERD_BASE: + return sink->_base_func + ? SerdStatus(sink->_base_func(NodeView(event->base.uri))) + : SERD_SUCCESS; + case SERD_PREFIX: + return sink->_prefix_func + ? SerdStatus(sink->_prefix_func(NodeView(event->prefix.name), + NodeView(event->prefix.uri))) + : SERD_SUCCESS; + case SERD_STATEMENT: + return sink->_statement_func + ? SerdStatus(sink->_statement_func( + StatementFlags(event->statement.flags), + StatementView(event->statement.statement))) + : SERD_SUCCESS; + case SERD_END: + return sink->_end_func + ? SerdStatus(sink->_end_func(NodeView(event->end.node))) + : SERD_SUCCESS; + } + + return SERD_SUCCESS; + } + + BaseFunc _base_func{}; + PrefixFunc _prefix_func{}; + StatementFunc _statement_func{}; + EndFunc _end_func{}; +}; + +/** + @} + @defgroup serdpp_canon Canon + @{ +*/ + +/// @copydoc SerdCanonFlag +enum class CanonFlag { + lax = SERD_CANON_LAX ///< @copydoc SERD_CANON_LAX +}; + +/// @copydoc SerdCanonFlags +using CanonFlags = Flags<CanonFlag>; + +/// @copydoc serd_canon_new +inline Sink +make_canon(const World& world, SinkView target, const CanonFlags flags) +{ + return Sink{serd_canon_new(world.cobj(), target.cobj(), flags)}; +} + +/** + @} + @defgroup serdpp_filter Filter + @{ +*/ + +/// @copydoc serd_filter_new +inline Sink +make_filter(const World& world, + SinkView target, + Optional<NodeView> subject, + Optional<NodeView> predicate, + Optional<NodeView> object, + Optional<NodeView> graph, + const bool inclusive) +{ + return Sink{serd_filter_new(world.cobj(), + target.cobj(), + subject.cobj(), + predicate.cobj(), + object.cobj(), + graph.cobj(), + inclusive)}; +} + +/** + @} + @} + @defgroup serdpp_env Environment + @{ +*/ + +template<class CObj> +using EnvHandle = + detail::StaticCopyable<CObj, serd_env_copy, serd_env_equals, serd_env_free>; + +/// Env wrapper +template<class CObj> +class EnvWrapper : public EnvHandle<CObj> +{ +public: + /// Return the base URI + NodeView base_uri() const + { + return NodeView(serd_env_base_uri(this->cobj())); + } + + /// Set the base URI + Status set_base_uri(const StringView& uri) + { + return Status(serd_env_set_base_uri(this->cobj(), uri)); + } + + /// Set a namespace prefix + Status set_prefix(StringView name, StringView uri) + { + return Status(serd_env_set_prefix(this->cobj(), name, uri)); + } + + /// Expand `node` into an absolute URI if possible + Optional<Node> expand(const NodeView& node) const + { + return Node{serd_env_expand_node(this->cobj(), node.cobj())}; + } + + /// Send all prefixes to `sink` + void write_prefixes(SinkView sink) const + { + serd_env_write_prefixes(this->cobj(), sink.cobj()); + } + +protected: + explicit EnvWrapper(std::unique_ptr<CObj> ptr) + : EnvHandle<CObj>{std::move(ptr)} + {} + + explicit EnvWrapper(CObj* const ptr) + : EnvHandle<CObj>{ptr} + {} +}; + +/// EnvView +using EnvView = EnvWrapper<const SerdEnv>; + +/// @copydoc SerdEnv +class Env : public EnvWrapper<SerdEnv> +{ +public: + explicit Env(World& world) + : EnvWrapper{serd_env_new(world.cobj(), SERD_EMPTY_STRING())} + {} + + explicit Env(World& world, const NodeView& base) + : EnvWrapper{serd_env_new(world.cobj(), base.string_view())} + {} +}; + +/** + @} + @defgroup serdpp_syntax_io Reading and Writing + @{ + @defgroup serdpp_byte_source Byte Source + @{ +*/ + +/// @copydoc SerdInputStream +class InputStream : public SerdInputStream +{ +public: + explicit InputStream(SerdInputStream stream) + : SerdInputStream{stream} + {} + + InputStream(const InputStream&) = delete; + InputStream& operator=(const InputStream&) = delete; + + InputStream(InputStream&&) = default; + InputStream& operator=(InputStream&&) = default; + + ~InputStream() { serd_close_input(this); } +}; + +static inline size_t +istream_read(void* const buf, + const size_t size, + const size_t nmemb, + void* const stream) noexcept +{ + std::istream& is = *static_cast<std::istream*>(stream); + const size_t len = size * nmemb; + + try { + is.read(static_cast<char*>(buf), static_cast<std::streamsize>(len)); + } catch (...) { + return 0u; + } + + return is.fail() ? 0u : len; +} + +static inline int +istream_error(void* const stream) +{ + std::istream& is = *static_cast<std::istream*>(stream); + + return !is.good(); +} + +inline InputStream +open_input_stream(std::istream& is) +{ + return InputStream{ + serd_open_input_stream(istream_read, istream_error, nullptr, &is)}; +} + +// InputStream +// open_input_string(StringView string) +// { +// return InputStream{ +// serd_open_input_string(stream(istream_read, istream_error, nullptr, +// &is)}; +// } + +/** + @} + @defgroup serdpp_reader Reader + @{ +*/ + +/// @copydoc SerdReaderFlag +enum class ReaderFlag { + lax = SERD_READ_LAX, ///< @copydoc SERD_READ_LAX + variables = SERD_READ_VARIABLES, ///< @copydoc SERD_READ_VARIABLES + relative = SERD_READ_RELATIVE, ///< @copydoc SERD_READ_RELATIVE + global = SERD_READ_GLOBAL, ///< @copydoc SERD_READ_GLOBAL +}; + +/// @copydoc SerdReaderFlags +using ReaderFlags = Flags<ReaderFlag>; + +/// @copydoc SerdReader +class Reader : public detail::StaticWrapper<SerdReader, serd_reader_free> +{ +public: + Reader(World& world, + const Syntax syntax, + const ReaderFlags flags, + Env& env, + SinkView sink, + size_t stack_size) + : StaticWrapper{serd_reader_new(world.cobj(), + SerdSyntax(syntax), + flags, + env.cobj(), + sink.cobj(), + stack_size)} + {} + + Status start(SerdInputStream& in, + const NodeView& input_name, + const size_t block_size) + { + return Status( + serd_reader_start(cobj(), &in, input_name.cobj(), block_size)); + } + + /// @copydoc serd_reader_read_chunk + Status read_chunk() { return Status(serd_reader_read_chunk(cobj())); } + + /// @copydoc serd_reader_read_document + Status read_document() { return Status(serd_reader_read_document(cobj())); } + + /// @copydoc serd_reader_finish + Status finish() { return Status(serd_reader_finish(cobj())); } + +private: + static inline size_t s_stream_read(void* buf, + size_t size, + size_t nmemb, + void* stream) noexcept + { + assert(size == 1); + (void)size; + + try { + auto* const s = static_cast<std::istream*>(stream); + s->read(static_cast<char*>(buf), std::streamsize(nmemb)); + if (s->good()) { + return nmemb; + } + } catch (...) { + } + + return 0; + } + + static inline int s_stream_error(void* stream) noexcept + { + try { + auto* const s = static_cast<std::istream*>(stream); + return (!(s->good())); + } catch (...) { + } + + return 1; + } +}; + +/** + @} + @defgroup serdpp_byte_sink Byte Sink + @{ +*/ + +/** + Sink function for string output. + + Similar semantics to `SerdWriteFunc` (and in turn `fwrite`), but takes char* + for convenience and may set errno for more informative error reporting than + supported by `SerdStreamErrorFunc`. + + @return Number of elements (bytes) written, which is short on error. +*/ +using WriteFunc = std::function<size_t(const char*, size_t)>; + +/// @copydoc SerdOutputStream +class OutputStream : public SerdOutputStream +{ +public: + explicit OutputStream(SerdOutputStream stream) + : SerdOutputStream{stream} + {} + + OutputStream(const OutputStream&) = delete; + OutputStream& operator=(const OutputStream&) = delete; + + OutputStream(OutputStream&&) = default; + OutputStream& operator=(OutputStream&&) = default; + + ~OutputStream() { close(); } + + /// @copydoc serd_close_output + Status close() { return static_cast<Status>(serd_close_output(this)); } +}; + +static inline size_t +ostream_write(const void* const buf, + const size_t size, + const size_t nmemb, + void* const stream) noexcept +{ + std::ostream& os = *static_cast<std::ostream*>(stream); + const size_t len = size * nmemb; + + try { + os.write(static_cast<const char*>(buf), std::streamsize(len)); + } catch (...) { + return 0u; + } + + return os.fail() ? 0u : len; +} + +inline OutputStream +open_output_stream(std::ostream& os) +{ + return OutputStream{ + serd_open_output_stream(ostream_write, nullptr, nullptr, &os)}; +} + +inline OutputStream +open_output_file(const StringView path) +{ + return OutputStream{serd_open_output_file(path.c_str())}; +} + +// /// @copydoc SerdOutputStream +// class OutputStream : public SerdOutputStream +// { +// public: +// /// Create a byte sink that writes to a function in blocks +// OutputStream(WriteFunc write_func, SerdStreamCloseFunc close_func) +// : StaticWrapper{serd_byte_sink_new_function(s_write, +// nullptr, +// this, +// block_size)} +// , _write_func{std::move(write_func)} +// {} + +// OutputStream(StringView filename, const size_t block_size) +// : StaticWrapper{serd_byte_sink_new_filename(filename.c_str(), +// block_size)} +// {} + +// /// Create a byte sink that writes to a function one byte at a time +// explicit OutputStream(WriteFunc write_func) +// : OutputStream{std::move(write_func), 1} +// {} + +// /// Create a byte sink from a standard output stream +// explicit OutputStream(std::ostream& stream) +// : StaticWrapper{serd_byte_sink_new_function(s_write, nullptr, this, 1)} +// , _write_func{[&](const char* str, size_t len) { +// stream.write(str, std::streamsize(len)); +// return stream.good() ? len : size_t(0); +// }} +// {} + +// Status close() { return static_cast<Status>(serd_byte_sink_close(cobj())); +// } + +// private: +// static inline size_t s_write(const void* buf, +// size_t size, +// size_t nmemb, +// void* sink) noexcept +// { +// assert(size == 1); +// (void)size; + +// auto* self = static_cast<OutputStream*>(sink); + +// try { +// return self->_write_func(static_cast<const char*>(buf), nmemb); +// } catch (...) { +// } + +// return 0; +// } + +// WriteFunc _write_func; +// }; + +/** + @} + @defgroup serdpp_writer Writer + @{ +*/ + +/// @copydoc SerdWriterFlag +enum class WriterFlag { + ascii = SERD_WRITE_ASCII, ///< @copydoc SERD_WRITE_ASCII + expanded = SERD_WRITE_EXPANDED, ///< @copydoc SERD_WRITE_EXPANDED + verbatim = SERD_WRITE_VERBATIM, ///< @copydoc SERD_WRITE_VERBATIM + terse = SERD_WRITE_TERSE, ///< @copydoc SERD_WRITE_TERSE + lax = SERD_WRITE_LAX, ///< @copydoc SERD_WRITE_LAX + rdf_type = SERD_WRITE_RDF_TYPE ///< @copydoc SERD_WRITE_RDF_TYPE +}; + +/// @copydoc SerdWriterFlags +using WriterFlags = Flags<WriterFlag>; + +/// @copydoc SerdWriter +class Writer : public detail::StaticWrapper<SerdWriter, serd_writer_free> +{ +public: + /** + Create a writer that writes syntax to the given byte sink. + + @param world The world that this writer is a part of. + + @param syntax Syntax to write. + + @param flags Flags to control writer behaviour. + + @param env Environment used for expansion and abbreviation. The writer + uses a reference to this, so the environment must outlive the writer. + + @param out Stream where output is written. The writer uses a reference to + this, so the stream must outlive the writer. + + @param block_size Number of bytes to write to the output stream at once. + */ + Writer(World& world, + const Syntax syntax, + const WriterFlags flags, + Env& env, + OutputStream& out, + const size_t block_size = 1u) + : StaticWrapper{serd_writer_new(world.cobj(), + SerdSyntax(syntax), + flags, + env.cobj(), + &out, + block_size)} + {} + + /// Return a sink that can be used to write data + SinkView sink() { return SinkView{serd_writer_sink(cobj())}; } + + /// @copydoc serd_writer_set_root_uri + Status set_root_uri(const StringView uri) + { + return Status(serd_writer_set_root_uri(cobj(), uri)); + } + + /// @copydoc serd_writer_finish + Status finish() { return Status(serd_writer_finish(cobj())); } +}; + +/** + @} + @} + @defgroup serdpp_storage Storage + @{ +*/ + +/** + @defgroup serdpp_iterator Iterator + @{ +*/ + +/// Empty class for end sentinels to provide an iterator-like interface +class EndCursor +{}; + +template<class CObj> +using CursorHandle = detail:: + DynamicCopyable<CObj, serd_cursor_copy, serd_cursor_equals, serd_cursor_free>; + +template<class CObj> +class CursorWrapper : public CursorHandle<CObj> +{ +public: + CursorWrapper(CursorWrapper&&) noexcept = default; + CursorWrapper(const CursorWrapper&) = default; + + CursorWrapper& operator=(CursorWrapper&&) noexcept = default; + CursorWrapper& operator=(const CursorWrapper&) = default; + + ~CursorWrapper() = default; + + const StatementView& operator*() const + { + _statement = StatementView{serd_cursor_get(this->cobj())}; + return _statement; + } + + const StatementView* operator->() const + { + _statement = StatementView{serd_cursor_get(this->cobj())}; + return &_statement; + } + + CursorWrapper<CObj>& operator++() + { + serd_cursor_advance(this->cobj()); + return *this; + } + +protected: + CursorWrapper(CObj* ptr, detail::Ownership ownership) + : CursorHandle<CObj>{{ptr, ownership}} + {} + + mutable StatementView _statement{}; +}; + +/// Cursor view +class CursorView : public CursorWrapper<const SerdCursor> +{ +public: + // explicit CursorView(const SerdCursor* const ptr) + // : CursorWrapper<const SerdCursor>{ptr, detail::Ownership::view} + // {} + + // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) + CursorView(const CursorWrapper<SerdCursor>& iter) + : CursorWrapper<const SerdCursor>{iter.cobj(), detail::Ownership::view} + {} +}; + +// using CursorView = CursorWrapper<const SerdCursor>; + +/// @copydoc SerdCursor +class Cursor : public CursorWrapper<SerdCursor> +{ +public: + explicit Cursor(CursorView iter) + : CursorWrapper{serd_cursor_copy(nullptr, iter.cobj()), + detail::Ownership::owned} + {} + + Cursor(SerdCursor* const ptr, const detail::Ownership ownership) + : CursorWrapper{ptr, ownership} + {} + + Cursor(Cursor&&) = default; + Cursor(const Cursor&) = default; + + Cursor& operator=(Cursor&&) = default; + Cursor& operator=(const Cursor&) = default; + + ~Cursor() = default; + + // Cursor& operator++() + // { + // serd_cursor_advance(this->cobj()); + // return *this; + // } +}; + +/** + @} + @defgroup serdpp_range Range + @{ +*/ + +/// @copydoc SerdDescribeFlag +enum class DescribeFlag { + no_type_first = SERD_NO_TYPE_FIRST ///< @copydoc SERD_NO_TYPE_FIRST +}; + +/// Bitwise OR of DescribeFlag values +using DescribeFlags = Flags<DescribeFlag>; + +/** + @} + @defgroup serdpp_model Model + @{ +*/ + +/// @copydoc SerdModelFlag +enum class ModelFlag { + store_graphs = SERD_STORE_GRAPHS, ///< @copydoc SERD_STORE_GRAPHS + store_carets = SERD_STORE_CARETS ///< @copydoc SERD_STORE_CARETS +}; + +/// Bitwise OR of ModelFlag values +using ModelFlags = Flags<ModelFlag>; + +/// @copydoc SerdStatementOrder +enum class StatementOrder { + SPO, ///< @copydoc SERD_ORDER_SPO + SOP, ///< @copydoc SERD_ORDER_SOP + OPS, ///< @copydoc SERD_ORDER_OPS + OSP, ///< @copydoc SERD_ORDER_OSP + PSO, ///< @copydoc SERD_ORDER_PSO + POS, ///< @copydoc SERD_ORDER_POS + GSPO, ///< @copydoc SERD_ORDER_GSPO + GSOP, ///< @copydoc SERD_ORDER_GSOP + GOPS, ///< @copydoc SERD_ORDER_GOPS + GOSP, ///< @copydoc SERD_ORDER_GOSP + GPSO, ///< @copydoc SERD_ORDER_GPSO + GPOS ///< @copydoc SERD_ORDER_GPOS +}; + +using ModelHandle = detail::StaticCopyable<SerdModel, + serd_model_copy, + serd_model_equals, + serd_model_free>; + +/// @copydoc SerdModel +class Model : public ModelHandle +{ +public: + using value_type = Statement; + using iterator = Cursor; + using const_iterator = Cursor; + + Model(World& world, + const StatementOrder default_order, + const ModelFlags flags) + : ModelHandle{serd_model_new(world.cobj(), + static_cast<SerdStatementOrder>(default_order), + flags)} + {} + + /// @copydoc serd_model_size + size_t size() const { return serd_model_size(cobj()); } + + /// @copydoc serd_model_empty + bool empty() const { return serd_model_empty(cobj()); } + + /// @copydoc serd_model_add_index + Status add_index(const StatementOrder order) + { + return static_cast<Status>( + serd_model_add_index(cobj(), static_cast<SerdStatementOrder>(order))); + } + + /// @copydoc serd_model_drop_index + Status drop_index(const StatementOrder order) + { + return static_cast<Status>( + serd_model_drop_index(cobj(), static_cast<SerdStatementOrder>(order))); + } + + /// @copydoc serd_model_insert + Status insert(StatementView s) + { + return static_cast<Status>(serd_model_insert(cobj(), s.cobj())); + } + + /// @copydoc serd_model_add + Status insert(const NodeView& s, + const NodeView& p, + const NodeView& o, + Optional<NodeView> g = {}) + { + return static_cast<Status>( + serd_model_add(cobj(), s.cobj(), p.cobj(), o.cobj(), g.cobj())); + } + + /// @copydoc serd_model_insert_statements + Status insert_statements(Cursor&& range) + { + return static_cast<Status>( + serd_model_insert_statements(cobj(), range.cobj())); + } + + /** + Remove a statement from a model via an iterator. + + Calling this function invalidates all iterators on `model` except `iter`. + + @param iter Iterator to the element to erase. + + @returns An iterator to the statement following the erased statement, + or the end iterator if the statement was the last or an error occurred. + */ + Cursor erase(Cursor iter) + { + if (!serd_model_erase(cobj(), iter.cobj())) { + return iter; + } + + return iter; + } + + Cursor erase(const CursorView& iter) + { + Cursor iter_copy{iter}; + + if (!serd_model_erase(cobj(), iter_copy.cobj())) { + return iter_copy; + } + + return iter_copy; + } + + /** + Remove a range from a model. + + Calling this function invalidates all iterators on `model` except `iter`. + + @param range Range to erase. + */ + Status erase_statements(Cursor range) + { + return static_cast<Status>( + serd_model_erase_statements(cobj(), range.cobj())); + } + + class Range + { + public: + Range(Cursor begin, Cursor end) + : _begin(std::move(begin)) + , _end(std::move(end)) + {} + + const Cursor& begin() const { return _begin; } + Cursor& begin() { return _begin; } + const Cursor& end() const { return _end; } + + private: + Cursor _begin; + Cursor _end; + }; + + /// @copydoc serd_model_find + Range find(Optional<NodeView> s, + Optional<NodeView> p, + Optional<NodeView> o, + Optional<NodeView> g = {}) const + { + return Range{ + Cursor{serd_model_find(cobj(), s.cobj(), p.cobj(), o.cobj(), g.cobj()), + detail::Ownership::owned}, + end()}; + } + + /// @copydoc serd_model_get + Optional<NodeView> get(Optional<NodeView> s, + Optional<NodeView> p, + Optional<NodeView> o, + Optional<NodeView> g = {}) const + { + return NodeView( + serd_model_get(cobj(), s.cobj(), p.cobj(), o.cobj(), g.cobj())); + } + + /// @copydoc serd_model_get_statement + Optional<StatementView> get_statement(Optional<NodeView> s, + Optional<NodeView> p, + Optional<NodeView> o, + Optional<NodeView> g = {}) const + { + return StatementView( + serd_model_get_statement(cobj(), s.cobj(), p.cobj(), o.cobj(), g.cobj())); + } + + /// @copydoc serd_model_ask + bool ask(Optional<NodeView> s, + Optional<NodeView> p, + Optional<NodeView> o, + Optional<NodeView> g = {}) const + { + return serd_model_ask(cobj(), s.cobj(), p.cobj(), o.cobj(), g.cobj()); + } + + /// @copydoc serd_model_count + size_t count(Optional<NodeView> s, + Optional<NodeView> p, + Optional<NodeView> o, + Optional<NodeView> g = {}) const + { + return serd_model_count(cobj(), s.cobj(), p.cobj(), o.cobj(), g.cobj()); + } + + /// @copydoc serd_model_begin_ordered + Cursor begin_ordered(StatementOrder order) const + { + return Cursor( + serd_model_begin_ordered(cobj(), static_cast<SerdStatementOrder>(order)), + detail::Ownership::owned); + } + + /// @copydoc serd_model_begin + iterator begin() const + { + return iterator(serd_model_begin(cobj()), detail::Ownership::owned); + } + + /// @copydoc serd_model_end + iterator end() const + { + // TODO: cache? + return iterator(serd_cursor_copy(nullptr, serd_model_end(cobj())), + detail::Ownership::owned); + // return iterator(serd_model_end(cobj()), detail::Ownership::view); + } + +private: + friend class Optional<Model>; + + explicit Model(std::nullptr_t) + : StaticCopyable{nullptr} + {} +}; + +/** + @} + @defgroup serdpp_inserter Inserter + @{ +*/ + +/** + Create an inserter that inserts statements into a model. + + @param model The model to insert received statements into. +*/ +inline Sink +make_inserter(Model& model) +{ + return Sink{serd_inserter_new(model.cobj(), nullptr)}; +} + +/** + Create an inserter that inserts statements into a specific graph in a model. + + @param model The model to insert received statements into. + + @param default_graph The default graph to set for any statements that have + no graph. This allows, for example, loading a Turtle document into an + isolated graph in the model. +*/ +inline Sink +make_inserter(Model& model, NodeView default_graph) +{ + return Sink{serd_inserter_new(model.cobj(), default_graph.cobj())}; +} + +/** + @} + @defgroup serdpp_validator Validator + @{ +*/ + +/// @copydoc SerdValidatorCheck +enum class ValidatorCheck : uint64_t { + /// @copydoc SERD_CHECK_NOTHING + nothing, + + /// @copydoc SERD_CHECK_ALL_VALUES_FROM + all_values_from = SERD_CHECK_ALL_VALUES_FROM, + + /// @copydoc SERD_CHECK_ANY_URI + any_uri = SERD_CHECK_ANY_URI, + + /// @copydoc SERD_CHECK_CARDINALITY_EQUAL + cardinality_equal = SERD_CHECK_CARDINALITY_EQUAL, + + /// @copydoc SERD_CHECK_CARDINALITY_MAX + cardinality_max = SERD_CHECK_CARDINALITY_MAX, + + /// @copydoc SERD_CHECK_CARDINALITY_MIN + cardinality_min = SERD_CHECK_CARDINALITY_MIN, + + /// @copydoc SERD_CHECK_CLASS_CYCLE + class_cycle = SERD_CHECK_CLASS_CYCLE, + + /// @copydoc SERD_CHECK_CLASS_LABEL + class_label = SERD_CHECK_CLASS_LABEL, + + /// @copydoc SERD_CHECK_DATATYPE_PROPERTY + datatype_property = SERD_CHECK_DATATYPE_PROPERTY, + + /// @copydoc SERD_CHECK_DATATYPE_TYPE + datatype_type = SERD_CHECK_DATATYPE_TYPE, + + /// @copydoc SERD_CHECK_DEPRECATED_CLASS + deprecated_class = SERD_CHECK_DEPRECATED_CLASS, + + /// @copydoc SERD_CHECK_DEPRECATED_PROPERTY + deprecated_property = SERD_CHECK_DEPRECATED_PROPERTY, + + /// @copydoc SERD_CHECK_FUNCTIONAL_PROPERTY + functional_property = SERD_CHECK_FUNCTIONAL_PROPERTY, + + /// @copydoc SERD_CHECK_INSTANCE_LITERAL + instance_literal = SERD_CHECK_INSTANCE_LITERAL, + + /// @copydoc SERD_CHECK_INSTANCE_TYPE + instance_type = SERD_CHECK_INSTANCE_TYPE, + + /// @copydoc SERD_CHECK_INVERSE_FUNCTIONAL_PROPERTY + inverse_functional_property = SERD_CHECK_INVERSE_FUNCTIONAL_PROPERTY, + + /// @copydoc SERD_CHECK_LITERAL_INSTANCE + literal_instance = SERD_CHECK_LITERAL_INSTANCE, + + /// @copydoc SERD_CHECK_LITERAL_MAX_EXCLUSIVE + literal_max_exclusive = SERD_CHECK_LITERAL_MAX_EXCLUSIVE, + + /// @copydoc SERD_CHECK_LITERAL_MAX_INCLUSIVE + literal_max_inclusive = SERD_CHECK_LITERAL_MAX_INCLUSIVE, + + /// @copydoc SERD_CHECK_LITERAL_MIN_EXCLUSIVE + literal_min_exclusive = SERD_CHECK_LITERAL_MIN_EXCLUSIVE, + + /// @copydoc SERD_CHECK_LITERAL_MIN_INCLUSIVE + literal_min_inclusive = SERD_CHECK_LITERAL_MIN_INCLUSIVE, + + /// @copydoc SERD_CHECK_LITERAL_PATTERN + literal_pattern = SERD_CHECK_LITERAL_PATTERN, + + /// @copydoc SERD_CHECK_LITERAL_RESTRICTION + literal_restriction = SERD_CHECK_LITERAL_RESTRICTION, + + /// @copydoc SERD_CHECK_LITERAL_VALUE + literal_value = SERD_CHECK_LITERAL_VALUE, + + /// @copydoc SERD_CHECK_OBJECT_PROPERTY + object_property = SERD_CHECK_OBJECT_PROPERTY, + + /// @copydoc SERD_CHECK_PLAIN_LITERAL_DATATYPE + plain_literal_datatype = SERD_CHECK_PLAIN_LITERAL_DATATYPE, + + /// @copydoc SERD_CHECK_PREDICATE_TYPE + predicate_type = SERD_CHECK_PREDICATE_TYPE, + + /// @copydoc SERD_CHECK_PROPERTY_CYCLE + property_cycle = SERD_CHECK_PROPERTY_CYCLE, + + /// @copydoc SERD_CHECK_PROPERTY_DOMAIN + property_domain = SERD_CHECK_PROPERTY_DOMAIN, + + /// @copydoc SERD_CHECK_PROPERTY_LABEL + property_label = SERD_CHECK_PROPERTY_LABEL, + + /// @copydoc SERD_CHECK_PROPERTY_RANGE + property_range = SERD_CHECK_PROPERTY_RANGE, + + /// @copydoc SERD_CHECK_SOME_VALUES_FROM + some_values_from = SERD_CHECK_SOME_VALUES_FROM, +}; + +/// @copydoc SerdValidator +class Validator + : public detail::StaticWrapper<SerdValidator, serd_validator_free> +{ +public: + /// Create a new validator with no checks enabled + explicit Validator(World& world) + : StaticWrapper{serd_validator_new(world.cobj())} + {} + + /// @copydoc serd_validator_enable_checks + Status enable_checks(StringView pattern) + { + return static_cast<Status>( + serd_validator_enable_checks(cobj(), pattern.c_str())); + } + + /// @copydoc serd_validator_disable_checks + Status disable_checks(StringView pattern) + { + return static_cast<Status>( + serd_validator_disable_checks(cobj(), pattern.c_str())); + } + + /** + Validate all statements in a specific graph in a model. + + This performs validation based on the XSD, RDF, RDFS, and OWL + vocabularies. All necessary data, including those vocabularies and any + property/class definitions that use them, are assumed to be in the model. + + Validation errors are reported to the world's error sink. + + @param model The model to validate. + + @return @ref Status::success if no errors are found, or @ref + Status::bad_data if validation checks failed. + */ + Status validate(const Model& model, NodeView graph, EnvView env) + { + return static_cast<Status>( + serd_validate(cobj(), model.cobj(), graph.cobj(), env.cobj())); + } + + /** + Validate all statements in a specific graph in a model. + + This performs the same validation as the other overload with a graph, but + does not take an env. URIs in the log output will not be abbreviated. + */ + Status validate(const Model& model, NodeView graph) + { + return static_cast<Status>( + serd_validate(cobj(), model.cobj(), graph.cobj(), nullptr)); + } + + /** + Validate all statements in a model. + + This overload validates all statements in any graph in the model. + */ + Status validate(const Model& model) + { + return static_cast<Status>( + serd_validate(cobj(), model.cobj(), nullptr, nullptr)); + } +}; + +/** + @} + @} + @} +*/ + +} // namespace serd + +#endif // SERD_SERD_HPP diff --git a/bindings/cpp/meson.build b/bindings/cpp/meson.build new file mode 100644 index 00000000..200bb13e --- /dev/null +++ b/bindings/cpp/meson.build @@ -0,0 +1,77 @@ +versioned_cpp_name = 'serdpp' + version_suffix + +# Set ultra strict warnings for developers, if requested +cpp_suppressions = [] +if get_option('strict') + if cpp.get_id() == 'clang' + cpp_suppressions += [ + '-Wno-documentation-unknown-command', + '-Wno-format-nonliteral', + '-Wno-nullability-extension', + '-Wno-padded', + ] + elif cpp.get_id() == 'gcc' + cpp_suppressions += [ + '-Wno-abi-tag', + '-Wno-float-equal', + '-Wno-multiple-inheritance', + '-Wno-padded', + '-Wno-switch-default', + ] + elif cpp.get_id() == 'msvc' + cpp_suppressions += [ + '/wd4355', # 'this' used in base member initializer list + '/wd4571', # structured exceptions are no longer caught + '/wd4623', # default constructor implicitly deleted + '/wd4625', # copy constructor implicitly deleted + '/wd4626', # assignment operator implicitly deleted + '/wd4710', # function not inlined + '/wd4868', # may not enforce left-to-right evaluation order + '/wd5026', # move constructor implicitly deleted + '/wd5027', # move assignment operator implicitly deleted + ] + endif +endif + +exess_cpp_args = cpp.get_supported_arguments(cpp_suppressions) + +cpp_headers = [ + 'include/serd/Flags.hpp', + 'include/serd/Optional.hpp', + 'include/serd/StringView.hpp', + 'include/serd/serd.hpp', +] + +cpp_detail_headers = [ + 'include/serd/detail/Copyable.hpp', + 'include/serd/detail/Wrapper.hpp', +] + +cpp_header_files = files(cpp_headers) +cpp_detail_header_files = files(cpp_detail_headers) + +serdpp_dep = declare_dependency( + include_directories: include_directories(['include']), + link_with: libserd) + +pkg.generate( + description: 'C++ bindings for serd', + filebase: versioned_cpp_name, + name: 'Serdpp', + subdirs: [versioned_cpp_name], + version: meson.project_version()) + +# Install headers to a versioned include directory +install_headers(cpp_header_files, subdir: versioned_cpp_name / 'serd') +install_headers(cpp_detail_header_files, + subdir: versioned_cpp_name / 'serd/detail') + +cpp_test_args = prog_args + cpp.get_supported_arguments(['-Wno-float-equal']) + +test('serd.hpp', + executable('test_serd_hpp', + 'test/test_serd_hpp.cpp', + include_directories: include_directories(['include']), + cpp_args: exess_cpp_args + cpp_test_args, + dependencies: [serd_dep, serdpp_dep]), + suite: ['bindings', 'cpp']) diff --git a/bindings/cpp/test/.clang-tidy b/bindings/cpp/test/.clang-tidy new file mode 100644 index 00000000..e71d5f54 --- /dev/null +++ b/bindings/cpp/test/.clang-tidy @@ -0,0 +1,30 @@ +Checks: > + *, + -*-magic-numbers, + -*-non-private-member-variables-in-classes, + -*-uppercase-literal-suffix, + -altera-struct-pack-align, + -cert-dcl50-cpp, + -cppcoreguidelines-pro-bounds-array-to-pointer-decay, + -cppcoreguidelines-pro-bounds-pointer-arithmetic, + -cppcoreguidelines-pro-type-vararg, + -fuchsia-default-arguments-calls, + -fuchsia-default-arguments-declarations, + -fuchsia-multiple-inheritance, + -fuchsia-overloaded-operator, + -google-readability-todo, + -google-runtime-references, + -hicpp-named-parameter, + -hicpp-no-array-decay, + -hicpp-signed-bitwise, + -hicpp-vararg, + -llvmlibc-*, + -misc-no-recursion, + -modernize-use-trailing-return-type, + -performance-unnecessary-value-param, + -readability-function-cognitive-complexity, + -readability-implicit-bool-conversion, + -readability-named-parameter, +WarningsAsErrors: '*' +HeaderFilterRegex: '*.hpp' +FormatStyle: file diff --git a/bindings/cpp/test/test_serd_hpp.cpp b/bindings/cpp/test/test_serd_hpp.cpp new file mode 100644 index 00000000..3f919b31 --- /dev/null +++ b/bindings/cpp/test/test_serd_hpp.cpp @@ -0,0 +1,823 @@ +/* + Copyright 2018-2021 David Robillard <d@drobilla.net> + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted, provided that the above + copyright notice and this permission notice appear in all copies. + + THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +*/ + +#undef NDEBUG + +#include "serd/serd.hpp" + +#include <algorithm> +#include <array> +#include <cassert> +#include <cstdint> +#include <cstring> +#include <fstream> // IWYU pragma: keep +#include <iostream> +#include <map> +#include <sstream> +#include <stdexcept> +#include <string> +#include <type_traits> +#include <utility> + +template<class T> +static int +test_move_only(T&& obj) +{ + static_assert(!std::is_copy_constructible<T>::value, ""); + static_assert(!std::is_copy_assignable<T>::value, ""); + + const auto* const ptr = obj.cobj(); + + // Move construct + T moved{std::forward<T>(obj)}; + assert(moved.cobj() == ptr); + assert(!obj.cobj()); // NOLINT + + // Move assign + obj = std::move(moved); + assert(obj.cobj() == ptr); + assert(!moved.cobj()); // NOLINT + + return 0; +} + +template<class T> +static int +test_copy_move(const T& obj) +{ + T copy{obj}; + assert(copy == obj); + + T moved{std::move(copy)}; + assert(moved == obj); + assert(copy != obj); // NOLINT + + T copy_assigned{obj}; + copy_assigned = obj; + assert(copy_assigned == obj); + + T move_assigned{obj}; + move_assigned = std::move(copy_assigned); + assert(move_assigned == obj); + assert(copy_assigned != obj); // NOLINT + + return 0; +} + +static int +test_operators() +{ + int st = 0; + + serd::World world; + + serd::Model model( + world, serd::StatementOrder::SPO, serd::ModelFlag::store_carets); + + model.insert(serd::Statement{serd::make_uri("http://example.org/s"), + serd::make_uri("http://example.org/p"), + serd::make_uri("http://example.org/o"), + serd::Caret{serd::make_uri("test.ttl"), 1, 1}}); + + serd::Sink sink{world}; + serd::Env env{world}; + + std::ostringstream stream; + + // st |= test_move_only(serd::World{}); + st |= test_copy_move(serd::Statement{*model.begin()}); + st |= + test_copy_move(serd::Caret{serd::make_uri("http://example.org/doc"), 1, 2}); + st |= test_copy_move(model.begin()->caret()); + st |= test_copy_move(serd::Env{world}); + st |= test_move_only( + serd::Reader{world, serd::Syntax::Turtle, {}, env, sink, 4096}); + st |= test_copy_move(model.begin()); + // st |= test_copy_move(model.all()); + // Sink + st |= test_copy_move(model); + // st |= test_move_only(serd::Inserter{model, env}); + // st |= test_move_only(serd::Sink{}); + + st |= test_copy_move(serd::Env{world}); + + return st; +} + +template<class Value> +static int +test_optional(const Value& value, const Value& other) +{ + test_copy_move(value); + + // Truthiness + assert(!serd::Optional<Value>()); + // assert(!serd::Optional<Value>(nullptr)); + assert(serd::Optional<Value>(value)); + + // Comparison and general sanity + serd::Optional<Value> optional{value}; + assert(optional); + assert(optional == value); + assert(optional != other); + assert(*optional == value); + assert(optional.cobj() != value.cobj()); // non-const, must be a copy + + // Reset + optional.reset(); + assert(!optional); + assert(!optional.cobj()); + + // Copying and moving + Value nonconst = value; + const auto* c_ptr = nonconst.cobj(); + + optional = nonconst; + serd::Optional<Value> copied{optional}; + assert(copied == nonconst); + assert(copied.cobj() != c_ptr); + + optional = std::move(nonconst); + serd::Optional<Value> moved{std::move(optional)}; + assert(moved.cobj() == c_ptr); + assert(!optional); // NOLINT + + serd::Optional<Value> copy_assigned; + copy_assigned = optional; + assert(copy_assigned == optional); + assert(copy_assigned.cobj() != c_ptr); + + serd::Optional<Value> move_assigned; + move_assigned = std::move(moved); + assert(move_assigned.cobj() == c_ptr); + assert(!optional); + + serd::Optional<Value> nullopt_assigned; + nullopt_assigned = {}; + assert(!nullopt_assigned.cobj()); + + return 0; +} + +static int +test_optional() +{ + test_optional(serd::make_string("value"), serd::make_string("other")); + + { + serd::World world; + + serd::Model value{world, serd::StatementOrder::SPO, {}}; + value.insert(serd::make_uri("http://example.org/s1"), + serd::make_uri("http://example.org/p1"), + serd::make_uri("http://example.org/o1")); + + serd::Model other(world, serd::StatementOrder::SPO, {}); + value.insert(serd::make_uri("http://example.org/s2"), + serd::make_uri("http://example.org/p2"), + serd::make_uri("http://example.org/o2")); + + test_optional(value, other); + } + + return 0; +} + +static int +test_node(const serd::Node& node) +{ + test_copy_move(node); + + if (node.datatype()) { + return test_node(*node.datatype()); + } + + if (node.language()) { + return test_node(*node.language()); + } + + return 0; +} + +static int +test_string() +{ + assert(!strcmp(serd::strerror(serd::Status::unknown_error), "Unknown error")); + + return 0; +} + +static int +test_stringview() +{ + const serd::StringView hello{"hello"}; + + assert(hello.front() == 'h'); + assert(hello.back() == 'o'); + + assert(*hello.begin() == 'h'); + assert(*hello.end() == '\0'); + assert(*(hello.end() - 1) == 'o'); + assert(*hello.cbegin() == 'h'); + assert(*hello.cend() == '\0'); + assert(*(hello.cend() - 1) == 'o'); + + assert(hello[0] == 'h'); + assert(hello[1] == 'e'); + assert(hello.at(0) == 'h'); + assert(hello.at(1) == 'e'); + assert(hello.substr(2) == "llo"); + + assert(hello.str() == "hello"); + assert(std::string(hello) == "hello"); + assert(!strcmp(static_cast<const char*>(hello), "hello")); + + std::stringstream ss; + ss << hello; + assert(ss.str() == "hello"); + + bool threw = false; + try { + hello.at(6); + } catch (const std::out_of_range&) { + threw = true; + } + assert(threw); + + try { + hello.substr(6); + } catch (const std::out_of_range&) { + threw = true; + } + assert(threw); + + assert(serd::StringView{} == serd::StringView{}); // NOLINT + assert(hello == "hello"); + assert(hello == std::string{"hello"}); + assert(hello == serd::StringView{"hello"}); + + assert(hello != "world"); + assert(hello != std::string{"world"}); + assert(hello != serd::StringView{"world"}); + + assert(serd::StringView{"a"}.compare(serd::StringView{"ab"}) < 0); + assert(serd::StringView{"ab"}.compare(serd::StringView{"a"}) > 0); + assert(serd::StringView{"ab"}.compare(serd::StringView{"ab"}) == 0); + + assert(hello < serd::StringView{"world"}); + assert(hello < std::string{"world"}); + assert(hello < "world"); + + assert(!(hello < serd::StringView{"apple"})); + assert(!(hello < std::string{"apple"})); + assert(!(hello < "apple")); + + return 0; +} + +// FIXME +#if 0 +static int +test_base64() +{ + const std::vector<uint8_t> data{1, 1, 2, 3, 5}; + + const auto encoded = serd::base64_encode(data); + const auto decoded = serd::base64_decode(encoded); + + assert(decoded == data); + + return 0; +} +#endif + +static int +test_syntax() +{ + assert(serd::syntax_by_name("Turtle") == serd::Syntax::Turtle); + assert(serd::guess_syntax("foo.trig") == serd::Syntax::TriG); + assert(!serd::syntax_has_graphs(serd::Syntax::NTriples)); + return 0; +} + +static int +test_nodes() +{ + const auto type = serd::make_uri("http://example.org/Type"); + const auto base = serd::make_uri("http://example.org/"); + const auto root = serd::make_uri("http://example.org/"); + + assert(base.type() == serd::NodeType::URI); + assert(base.str() == "http://example.org/"); + assert(base.size() == strlen("http://example.org/")); + assert(base == root); + assert(base < type); + assert(!base.empty()); + assert(std::count(base.begin(), base.end(), '/') == 3); + + const auto relative = serd::make_uri("rel/uri"); + // const auto resolved = relative.resolve(base); + // assert(static_cast<std::string>(resolved) == "http://example.org/rel/uri"); + // assert(static_cast<serd::StringView>(resolved) == + // "http://example.org/rel/uri"); + + const auto string = serd::make_string("hello\n\"world\""); + + const auto number = serd::make_integer(42); + assert(number.datatype() == + serd::make_uri("http://www.w3.org/2001/XMLSchema#integer")); + + const auto tagged = serd::make_plain_literal("hallo", "de"); + assert(tagged.language() == serd::make_string("de")); + + assert(!test_node(serd::make_string("hello"))); + assert(!test_node(serd::make_plain_literal("hello", "en"))); + assert(!test_node(serd::make_typed_literal("hello", serd::StringView(type)))); + assert(!test_node(serd::make_blank("blank"))); + assert(!test_node(serd::make_uri("http://example.org/thing"))); + assert(!test_node(serd::make_file_uri("/foo/bar", "host"))); + assert(!test_node(serd::make_file_uri("/foo/bar"))); + assert(!test_node(serd::make_file_uri("/foo/bar", "host"))); + assert(!test_node(serd::make_file_uri("/foo/bar"))); + assert(!test_node(serd::make_decimal(1.2))); + assert(!test_node(serd::make_decimal(3.4))); + assert(!test_node(serd::make_integer(56))); + assert(!test_node(serd::make_base64("blob", 4))); + + assert(serd::get<bool>(serd::make(true)) == true); + assert(serd::get<bool>(serd::make(false)) == false); + assert(serd::get<double>(serd::make(1.5)) == 1.5); + assert(serd::get<double>(serd::make(-2.5)) == -2.5); + assert(serd::get<float>(serd::make(1.2f)) == 1.2f); + assert(serd::get<float>(serd::make(-2.5f)) == -2.5f); + assert(serd::get<int64_t>(serd::make(12)) == 12); + assert(serd::get<int64_t>(serd::make(-34)) == -34); + + return 0; +} + +static int +test_uri() +{ + const auto uri = serd::make_uri("file:/path"); + const auto no_authority = serd::URI(serd::StringView(uri)); + assert(no_authority.scheme() == "file"); + assert(!no_authority.authority().data()); + assert(no_authority.path() == "/path"); + + const auto empty_authority = serd::URI("file:///path"); + assert(empty_authority.scheme() == "file"); + assert(empty_authority.authority().data()); + assert(empty_authority.authority().empty()); + assert(empty_authority.path() == "/path"); + + const auto base = serd::URI("http://example.org/base/"); + assert(base.scheme() == "http"); + assert(base.authority() == "example.org"); + assert(!base.path_prefix().data()); + assert(base.path() == "/base/"); + assert(!base.query().data()); + assert(!base.fragment().data()); + + const auto rel = serd::URI("relative/path?query#fragment"); + assert(!rel.scheme().data()); + assert(!rel.authority().data()); + assert(!rel.path_prefix().data()); + assert(rel.path() == "relative/path"); + assert(rel.query() == "query"); + assert(rel.fragment() == "#fragment"); + + const auto resolved = rel.resolve(base); + assert(resolved.scheme() == "http"); + assert(resolved.authority() == "example.org"); + assert(resolved.path_prefix() == "/base/"); + assert(resolved.path() == "relative/path"); + assert(resolved.query() == "query"); + assert(resolved.fragment() == "#fragment"); + + assert(resolved.string() == + "http://example.org/base/relative/path?query#fragment"); + std::cerr << resolved.relative_string(base) << std::endl; + assert(resolved.relative_string(base) == "relative/path?query#fragment"); + + const auto domain = serd::URI("http://example.org/"); + assert(domain.relative_string(resolved) == "../../"); + assert(domain.relative_string(resolved, base) == domain.string()); + + auto local_file_uri = serd::parse_file_uri("file:///foo/%20bar"); + assert(local_file_uri == "/foo/ bar"); + + auto hostname = std::string(); + auto host_file_uri = serd::parse_file_uri("file://host/foo", &hostname); + assert(hostname == "host"); + assert(host_file_uri == "/foo"); + + assert(serd::uri_string_has_scheme("http://example.org/")); + assert(!serd::uri_string_has_scheme("foo/bar")); + + std::ostringstream ss; + ss << resolved; + assert(ss.str() == "http://example.org/base/relative/path?query#fragment"); + + return 0; +} + +static int +test_reader() +{ + serd::World world; + serd::Optional<serd::Node> base_uri; + serd::Optional<serd::Node> ns_name; + serd::Optional<serd::Node> ns_uri; + serd::Optional<serd::Node> ended_node; + size_t n_statements{}; + std::stringstream stream{}; + serd::Sink sink{world}; + + sink.set_base_func([&](serd::NodeView uri) { + base_uri = uri; + return serd::Status::success; + }); + + sink.set_prefix_func([&](serd::NodeView name, serd::NodeView uri) { + ns_name = name; + ns_uri = uri; + return serd::Status::success; + }); + + sink.set_statement_func( + [&](const serd::StatementFlags, const serd::Statement& statement) { + ++n_statements; + stream << statement.subject() << " " << statement.predicate() << " " + << statement.object() << std::endl; + return serd::Status::success; + }); + + sink.set_end_func([&](serd::NodeView node) { + ended_node = node; + return serd::Status::success; + }); + + // FIXME +#if 0 + serd::World world; + serd::Env env; + serd::Reader reader( + world, serd::Syntax::Turtle, serd::ReaderFlag::global, env, sink, 4096); + + const std::string input("@base <http://example.org/base> ." + "@prefix eg: <http://example.org/> ." + "eg:s eg:p [ eg:p2 eg:o2 ] ."); + + // Read from string + serd::InputStream string_source = serd::open_string(input); + reader.start(string_source); + reader.read_document(); + + assert(n_statements == 2); + assert(stream.str() == "http://example.org/s http://example.org/p b1\n" + "b1 http://example.org/p2 http://example.org/o2\n"); + + assert(base_uri == serd::make_uri("http://example.org/base")); + assert(ns_name == serd::make_string("eg")); + assert(ns_uri == serd::make_uri("http://example.org/")); + + // Read from C++ stream + std::stringstream ss("eg:s eg:p eg:o3 , _:blank ."); + serd::ByteSource byte_source(ss); + stream.str(""); + reader.start(byte_source); + assert(reader.read_chunk() == serd::Status::success); + assert(reader.read_chunk() != serd::Status::success); + + assert(n_statements == 4); + assert(stream.str() == + "http://example.org/s http://example.org/p http://example.org/o3\n" + "http://example.org/s http://example.org/p blank\n"); + + assert(reader.finish() == serd::Status::success); +#endif + + return 0; +} + +static serd::Status +write_test_doc(serd::Writer& writer) +{ + const auto& sink = writer.sink(); + + const auto blank = serd::make_blank("b1"); + sink.base(serd::make_uri("http://drobilla.net/base/")); + sink.prefix(serd::make_string("eg"), serd::make_uri("http://example.org/")); + sink.write(serd::StatementFlag::anon_O, + serd::make_uri("http://drobilla.net/base/s"), + serd::make_uri("http://example.org/p"), + blank); + sink.statement({}, + serd::Statement(blank, + serd::make_uri("http://example.org/p2"), + serd::make_uri("http://drobilla.net/o"))); + sink.end(blank); + + return writer.finish(); +} + +static const char* const writer_test_doc = + "@base <http://drobilla.net/base/> .\n" + "@prefix eg: <http://example.org/> .\n" + "\n" + "<http://drobilla.net/base/s>\n" + "\t<http://example.org/p> [\n" + "\t\t<http://example.org/p2> <http://drobilla.net/o>\n" + "\t] .\n"; + +static int +test_writer_ostream() +{ + serd::World world; + serd::Env env{world}; + + { + std::ostringstream stream; + serd::OutputStream out{serd::open_output_stream(stream)}; + serd::Writer writer(world, serd::Syntax::Turtle, {}, env, out); + + write_test_doc(writer); + assert(stream.str() == writer_test_doc); + } + + { + std::ofstream bad_file("/does/not/exist"); + bad_file.clear(); + bad_file.exceptions(std::ofstream::badbit); + + serd::OutputStream bad_file_out{serd::open_output_stream(bad_file)}; + serd::Writer writer(world, serd::Syntax::Turtle, {}, env, bad_file_out); + + const serd::Status st = + writer.sink().base(serd::make_uri("http://drobilla.net/base/")); + + assert(st == serd::Status::bad_write); + } + + return 0; +} + +static int +test_writer_string_sink() +{ +// FIXME +#if 0 + serd::World world; + serd::Env env; + std::string output; + + serd::ByteSink byte_sink{[&output](const char* str, size_t len) { + output += str; + return len; + }}; + + serd::Writer writer(world, serd::Syntax::Turtle, {}, env, byte_sink); + + write_test_doc(writer); + assert(output == writer_test_doc); +#endif + + return 0; +} + +static int +test_env() +{ + serd::World world; + serd::Env env{world, serd::make_uri("http://example.org/")}; + assert(env.base_uri() == serd::make_uri("http://example.org/")); + + env = serd::Env{world}; + + const auto base = serd::make_uri("http://drobilla.net/"); + env.set_base_uri(serd::StringView(base)); + assert(env.base_uri() == base); + + env.set_prefix("eg", "http://drobilla.net/"); + env.set_prefix("eg", "http://example.org/"); + + assert(env.expand(serd::make_uri("foo")) == + serd::make_uri("http://drobilla.net/foo")); + + serd::Env copied{env}; + assert(copied.cobj() != env.cobj()); + assert(copied.expand(serd::make_uri("foo")) == + serd::make_uri("http://drobilla.net/foo")); + + serd::Env assigned{world}; + assigned = env; + assert(assigned.cobj() != env.cobj()); + assert(assigned.expand(serd::make_uri("foo")) == + serd::make_uri("http://drobilla.net/foo")); + + serd::Sink sink{world}; + serd::Optional<serd::Node> ns_name; + serd::Optional<serd::Node> ns_uri; + + sink.set_prefix_func([&](serd::NodeView name, serd::NodeView uri) { + ns_name = name; + ns_uri = uri; + return serd::Status::success; + }); + + env.write_prefixes(sink); + assert(ns_name == serd::make_string("eg")); + assert(ns_uri == serd::make_uri("http://example.org/")); + + return 0; +} + +static int +test_statement() +{ + const auto s = serd::make_uri("http://example.org/s"); + const auto p = serd::make_uri("http://example.org/p"); + const auto o = serd::make_uri("http://example.org/o"); + const auto g = serd::make_uri("http://example.org/g"); + const auto cur = serd::Caret{serd::make_string("test"), 42, 53}; + + const auto t_statement = serd::Statement{s, p, o}; + + assert(t_statement.subject() == s); + assert(t_statement.predicate() == p); + assert(t_statement.object() == o); + assert(!t_statement.graph()); + assert(!t_statement.caret()); + + const auto q_statement = serd::Statement{s, p, o, g, cur}; + assert(q_statement.subject() == s); + assert(q_statement.predicate() == p); + assert(q_statement.object() == o); + assert(q_statement.graph() == g); + assert(q_statement.caret() == cur); + + assert(q_statement.node(serd::Field::subject) == s); + assert(q_statement.node(serd::Field::predicate) == p); + assert(q_statement.node(serd::Field::object) == o); + assert(q_statement.node(serd::Field::graph) == g); + + return 0; +} + +static int +test_model() +{ + serd::World world; + serd::Model model(world, serd::StatementOrder::SPO, {}); + + model.add_index(serd::StatementOrder::OPS); + + assert(model.empty()); + + const auto s = serd::make_uri("http://example.org/s"); + const auto p = serd::make_uri("http://example.org/p"); + const auto o1 = serd::make_uri("http://example.org/o1"); + const auto o2 = serd::make_uri("http://example.org/o2"); + + serd::NodeView b = world.get_blank(); + // auto r = b.resolve(s); + + model.insert(s, p, o1); + model.insert(serd::Statement{s, p, o2}); + + assert(!model.empty()); + assert(model.size() == 2); + assert(model.ask(s, p, o1)); + assert(model.count(s, p, o1) == 1); + assert(!model.ask(s, p, s)); + + size_t total_count = 0; + for (const auto& statement : model) { + assert(statement.subject() == s); + assert(statement.predicate() == p); + assert(statement.object() == o1 || statement.object() == o2); + ++total_count; + } + assert(total_count == 2); + + size_t o1_count = 0; + for (const auto& statement : model.find({}, {}, o1)) { + assert(statement.cobj()); + assert(statement.subject() == s); + assert(statement.predicate() == p); + assert(statement.object() == o1); + ++o1_count; + } + assert(o1_count == 1); + + size_t o2_count = 0; + for (const auto& statement : model.find({}, {}, o2)) { + assert(statement.subject() == s); + assert(statement.predicate() == p); + assert(statement.object() == o2); + ++o2_count; + } + assert(o2_count == 1); + + assert(model.get({}, p, o1) == s); + + const auto statement = model.get_statement(s, p, {}); + assert(statement); + assert(statement->subject() == s); + assert(statement->predicate() == p); + assert(statement->object() == o1); + + const auto range = model.find(s, p, {}); + assert(range.begin()->subject() == s); + assert(range.begin()->predicate() == p); + assert(range.begin()->object() == o1); + + serd::Model copy(model); + assert(copy == model); + + copy.insert(s, p, s); + assert(copy != model); + + return 0; +} + +static int +test_log() +{ + serd::World world; + bool called = false; + world.set_message_func([&called](const serd::LogLevel level, + const serd::LogFields& fields, + const std::string& msg) { + assert(fields.at("TEST_EXTRA") == "extra field"); + assert(level == serd::LogLevel::error); + assert(msg == "bad argument to something: 42\n"); + called = true; + return serd::Status::success; + }); + + const auto success = world.log(serd::LogLevel::error, + {{"TEST_EXTRA", "extra field"}}, + "bad argument to %s: %d\n", + "something", + 42); + + assert(called); + assert(success == serd::Status::success); + + world.set_message_func([](const serd::LogLevel, + const serd::LogFields&, + const std::string&) -> serd::Status { + throw std::runtime_error("error"); + }); + + const auto failure = world.log(serd::LogLevel::error, {}, "failure"); + assert(failure == serd::Status::unknown_error); + + return 0; +} + +int +main() +{ + using TestFunc = int (*)(); + + constexpr std::array<TestFunc, 14> tests{{test_operators, + test_optional, + test_nodes, + test_string, + test_stringview, + // test_base64, + test_syntax, + test_uri, + test_env, + test_reader, + test_writer_ostream, + test_writer_string_sink, + test_statement, + test_model, + test_log}}; + + int failed = 0; + for (const auto& test : tests) { + failed += test(); + } + + std::cerr << "Failed " << failed << " tests" << std::endl; + + return failed; +} |