浏览代码

AK: Add adopt_nonnull_own_or_enomem

This is basically a complement to adopt_nonnull_ref_or_enomem, and
simplifies boilerplate for try_create functions which just return ENOMEM
or the object based on whether it was able to allocate.
sin-ack 3 年之前
父节点
当前提交
8269e1a197
共有 1 个文件被更改,包括 18 次插入0 次删除
  1. 18 0
      AK/OwnPtr.h

+ 18 - 0
AK/OwnPtr.h

@@ -8,6 +8,9 @@
 
 
 #include <AK/NonnullOwnPtr.h>
 #include <AK/NonnullOwnPtr.h>
 #include <AK/RefCounted.h>
 #include <AK/RefCounted.h>
+#ifdef KERNEL
+#    include <Kernel/KResult.h>
+#endif
 
 
 namespace AK {
 namespace AK {
 
 
@@ -205,6 +208,17 @@ inline OwnPtr<T> adopt_own_if_nonnull(T* object)
     return {};
     return {};
 }
 }
 
 
+#ifdef KERNEL
+template<typename T>
+inline Kernel::KResultOr<NonnullOwnPtr<T>> adopt_nonnull_own_or_enomem(T* object)
+{
+    auto result = adopt_own_if_nonnull(object);
+    if (!result)
+        return ENOMEM;
+    return result.release_nonnull();
+}
+#endif
+
 template<typename T, class... Args>
 template<typename T, class... Args>
 requires(IsConstructible<T, Args...>) inline OwnPtr<T> try_make(Args&&... args)
 requires(IsConstructible<T, Args...>) inline OwnPtr<T> try_make(Args&&... args)
 {
 {
@@ -232,3 +246,7 @@ struct Traits<OwnPtr<T>> : public GenericTraits<OwnPtr<T>> {
 using AK::adopt_own_if_nonnull;
 using AK::adopt_own_if_nonnull;
 using AK::OwnPtr;
 using AK::OwnPtr;
 using AK::try_make;
 using AK::try_make;
+
+#ifdef KERNEL
+using AK::adopt_nonnull_own_or_enomem;
+#endif