@@ -272,6 +272,70 @@ namespace Slang
272
272
private:
273
273
T* m_ptr;
274
274
};
275
- }
276
275
276
+ // A pointer that can be transformed to hold either a weak reference or a strong reference.
277
+ template <typename T>
278
+ class TransformablePtr
279
+ {
280
+ private:
281
+ T* m_weakPtr = nullptr ;
282
+ RefPtr<T> m_strongPtr;
283
+
284
+ public:
285
+ TransformablePtr () = default ;
286
+ TransformablePtr (T* ptr) { *this = ptr; }
287
+ TransformablePtr (RefPtr<T> ptr) { *this = ptr; }
288
+ TransformablePtr (const TransformablePtr<T>& ptr) = default ;
289
+
290
+ void promoteToStrongReference () { m_strongPtr = m_weakPtr; }
291
+ void demoteToWeakReference () { m_strongPtr = nullptr ; }
292
+ bool isStrongReference () const { return m_strongPtr != nullptr ; }
293
+
294
+ T& operator *() const { return *m_weakPtr; }
295
+
296
+ T* operator ->() const { return m_weakPtr; }
297
+
298
+ T* Ptr () const { return m_weakPtr; }
299
+ T* get () const { return m_weakPtr; }
300
+
301
+ operator T*() const { return m_weakPtr; }
302
+ operator RefPtr<T>() const { return m_weakPtr; }
303
+
304
+
305
+ TransformablePtr<T>& operator =(T* ptr)
306
+ {
307
+ m_weakPtr = ptr;
308
+ m_strongPtr = ptr;
309
+ return *this ;
310
+ }
311
+ template <typename U>
312
+ TransformablePtr<T>& operator =(const RefPtr<U>& ptr)
313
+ {
314
+ m_weakPtr = ptr.Ptr ();
315
+ m_strongPtr = ptr;
316
+ return *this ;
317
+ }
318
+
319
+ HashCode getHashCode () const
320
+ {
321
+ // Note: We need a `RefPtr<T>` to hash the same as a `T*`,
322
+ // so that a `T*` can be used as a key in a dictionary with
323
+ // `RefPtr<T>` keys, and vice versa.
324
+ //
325
+ return Slang::getHashCode (m_weakPtr);
326
+ }
327
+
328
+ bool operator ==(const T* ptr) const { return m_weakPtr == ptr; }
329
+
330
+ bool operator !=(const T* ptr) const { return m_weakPtr != ptr; }
331
+
332
+ bool operator ==(RefPtr<T> const & ptr) const { return m_weakPtr == ptr.Ptr (); }
333
+
334
+ bool operator !=(RefPtr<T> const & ptr) const { return m_weakPtr != ptr.Ptr (); }
335
+
336
+ bool operator ==(TransformablePtr<T> const & ptr) const { return m_weakPtr == ptr.m_weakPtr ; }
337
+
338
+ bool operator !=(TransformablePtr<T> const & ptr) const { return m_weakPtr != ptr.m_weakPtr ; }
339
+ };
340
+ }
277
341
#endif
0 commit comments