1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
//! Blob support.
//!
//! Blobs are a way to share data with SWI-Prolog which does not fit
//! in any one of the built-in term types. They are stored in the
//! SWI-Prolog environment as a special kind of atom.
//!
//! This module, together with the various blob macros, implement
//! support for different classes of blobs.
//!
//! For all blob types, macros have been defined to easily define and
//! implement them. This allows your type to be used with
//! [Term::get](crate::term::Term::get),
//! [Term::put](crate::term::Term::put), and
//! [Term::unify](crate::term::Term::unify).
//!
//! # ArcBlob
//! This type of blob is a pointer to atomically reference counted
//! rust data. Upon getting, putting or unifying terms with data of
//! this type, only the pointer is transfered and reference counts are
//! updated.

//! ## Examples
//! Using the default implementation for `write` and `compare`:
//! ```
//! # use swipl::prelude::*;
//! # use std::sync::Arc;
//!
//! // note the keyword 'defaults' below - this makes sure that a
//! // default implementation of `ArcBlobImpl` is generated.
//! #[arc_blob("foo", defaults)]
//! struct Foo {
//!     num: u64
//! }
//!
//! fn do_something(term1: &Term, term2: &Term) -> PrologResult<()> {
//!     let arc = Arc::new(Foo{num: 42});
//!     term1.unify(&arc)?;
//!     let retrieved: Arc<Foo> = term1.get()?;
//!     assert_eq!(42, retrieved.num);
//!     term2.put(&retrieved)?;
//!
//!     Ok(())
//! }
//! ```
//!
//! Provide your own implementation for `write` and `compare`:
//! ```
//! # use swipl::prelude::*;
//! # use std::sync::Arc;
//! # use std::io::Write;
//! # use std::cmp::Ordering;
//!
//! #[arc_blob("foo")]
//! struct Foo {
//!     num: u64
//! }
//!
//! impl ArcBlobImpl for Foo {
//!     fn write(&self, stream: &mut PrologStream) -> std::io::Result<()> {
//!         write!(stream, "<foo {}>", self.num)
//!     }
//!
//!     fn compare(&self, other: &Self) -> Ordering {
//!         self.num.cmp(&other.num)
//!     }
//! }
//! ```
//!
//! # WrappedArcBlob
//! This type of blob is very similar to an [ArcBlob]. The difference
//! is that it is wrapped in a struct. This is done due to the
//! requirement that a trait from another crate can only be
//! implemented for your own types. This means that [ArcBlob] cannot
//! be directly implemented from code that depends on the `swipl`
//! crate for an `Arc` that comes out of another dependency. The
//! wrapper allows a trait to be implemented that does the job.
//!
//! ## Examples
//! Using the default implementation for `write` and `compare`:
//! ```
//! # use swipl::prelude::*;
//! # use std::sync::Arc;
//!
//! // Note that it is not possible to implement ArcBlob directly on a
//! // Vec<bool>, as it is not a type defined by us. That's why it
//! // needs to be wrapped.
//! wrapped_arc_blob!("foo", Foo, Vec<bool>, defaults);
//!
//! fn do_something(term1: &Term, term2: &Term) -> PrologResult<()> {
//!     let wrapped = Foo(Arc::new(vec![true,false,true]));
//!     term1.unify(&wrapped)?;
//!     let retrieved: Foo = term1.get()?;
//!     assert!(!retrieved[1]);
//!     term2.put(&retrieved)?;
//!
//!     Ok(())
//! }
//! ```
//!
//! Provide your own implementation for `write` and `compare`:
//! ```
//! # use swipl::prelude::*;
//! # use std::sync::Arc;
//! # use std::io::Write;
//! # use std::cmp::Ordering;
//!
//! wrapped_arc_blob!("foo", Foo, Vec<bool> );
//!
//! impl WrappedArcBlobImpl for Foo {
//!     fn write(this: &Vec<bool>, stream: &mut PrologStream) -> std::io::Result<()> {
//!         write!(stream, "<foo {:?}>",this)
//!     }
//!
//!     fn compare(this: &Vec<bool>, other: &Vec<bool>) -> Ordering {
//!         this.cmp(other)
//!     }
//! }
//! ```
//!
//! # CloneBlob
//! This type of blob copies its contents to and from SWI-Prolog when
//! getting, putting or unifying terms with the data.
//!
//! ## Examples
//! ```
//! # use swipl::prelude::*;
//!
//! // note the keyword 'defaults' below - this makes sure that a
//! // default implementation of `CloneBlobImpl` is generated.
//! // note also that the struct below derives Clone, which allows it
//! // to be used as a clone blob.
//! #[clone_blob("foo", defaults)]
//! #[derive(Clone)]
//! struct Foo {
//!     num: u64
//! }
//!
//! fn do_something(term1: &Term, term2: &Term) -> PrologResult<()> {
//!     let val = Foo{num: 42};
//!     term1.unify(&val)?;
//!     let retrieved: Foo = term1.get()?;
//!     assert_eq!(42, retrieved.num);
//!     term2.put(&retrieved)?;
//!
//!     Ok(())
//! }
//! ```
//!
//! Provide your own implementation for `write` and `compare`:
//! ```
//! # use swipl::prelude::*;
//! # use std::io::Write;
//! # use std::cmp::Ordering;
//!
//! #[clone_blob("foo")]
//! #[derive(Clone)]
//! struct Foo {
//!     num: u64
//! }
//!
//! impl CloneBlobImpl for Foo {
//!     fn write(&self, stream: &mut PrologStream) -> std::io::Result<()> {
//!         write!(stream, "<foo {}>", self.num)
//!     }
//!
//!     fn compare(&self, other: &Self) -> Ordering {
//!         self.num.cmp(&other.num)
//!     }
//! }
//! ```
//!
//! # wrapped CloneBlob
//! For convenience, there's also a
//! [wrapped_clone_blob!](crate::prelude::wrapped_clone_blob!) macro
//! for cases where we wish to generate a blob out of cloneable data
//! that is of a type defined in another crate. This is analogous to
//! the wrapped arc blob, except that no extra types are
//! required. There is no `WrappedCloneBlob`, instead, the wrapper
//! just implements CloneBlob directly.
//!
//! ## Examples
//! ```
//! # use swipl::prelude::*;
//!
//! wrapped_clone_blob!("foo", Foo, Vec<bool>, defaults);
//!
//! fn do_something(term1: &Term, term2: &Term) -> PrologResult<()> {
//!     let val = Foo(vec![true, false, true]);
//!     term1.unify(&val)?;
//!     let retrieved: Foo = term1.get()?;
//!     assert!(!retrieved[1]);
//!     term2.put(&retrieved)?;
//!
//!     Ok(())
//! }
//! ```
//!
//! Provide your own implementation for `write` and `compare`:
//! ```
//! # use swipl::prelude::*;
//! # use std::io::Write;
//! # use std::cmp::Ordering;
//!
//! wrapped_clone_blob!("foo", Foo, Vec<bool>);
//!
//! impl CloneBlobImpl for Foo {
//!     fn write(&self, stream: &mut PrologStream) -> std::io::Result<()> {
//!         write!(stream, "<foo {:?}>", self.0)
//!     }
//!
//!     fn compare(&self, other: &Self) -> Ordering {
//!         self.0.cmp(&other.0)
//!     }
//! }
//! ```

use std::cmp::Ordering;
use std::io::{self, Write};
use std::os::raw::{c_int, c_void};
use std::sync::Arc;

use crate::fli;
use crate::stream::*;
use crate::term::*;

/// Create a blob definition for use with the SWI-Prolog fli out of
/// the given components.
///
/// This is used by the various blob macros. You'll almost never have
/// to use this directly.
#[allow(clippy::too_many_arguments)]
pub fn create_blob_definition(
    name: &'static [u8],
    text: bool,
    unique: bool,
    nocopy: bool,
    acquire: Option<unsafe extern "C" fn(a: fli::atom_t)>,
    release: Option<unsafe extern "C" fn(a: fli::atom_t) -> c_int>,
    compare: Option<unsafe extern "C" fn(a: fli::atom_t, b: fli::atom_t) -> c_int>,
    write: Option<
        unsafe extern "C" fn(s: *mut fli::IOSTREAM, a: fli::atom_t, flags: c_int) -> c_int,
    >,
    save: Option<unsafe extern "C" fn(a: fli::atom_t, s: *mut fli::IOSTREAM) -> c_int>,
    load: Option<unsafe extern "C" fn(s: *mut fli::IOSTREAM) -> fli::atom_t>,
) -> fli::PL_blob_t {
    let last_char = name.last();
    if last_char.is_none() || *last_char.unwrap() != 0 {
        panic!("tried to register a blob definition with a name that does not end in a NULL");
    }

    let mut flags = 0;
    if text {
        flags |= fli::PL_BLOB_TEXT;
    }
    if unique {
        flags |= fli::PL_BLOB_UNIQUE;
    }
    if nocopy {
        flags |= fli::PL_BLOB_NOCOPY;
    }
    let mut result = unsafe { std::mem::zeroed::<fli::PL_blob_t>() };
    result.magic = fli::PL_BLOB_MAGIC as usize;
    result.flags = flags as usize;
    result.name = name.as_ptr() as *mut std::os::raw::c_char;
    result.acquire = acquire;
    result.release = release;
    result.compare = compare;
    result.write = write;
    result.save = save;
    result.load = load;

    result
}

/// Base type for [ArcBlob].
///
/// This allows `blob_name` to be available to implementors of
/// [ArcBlobImpl], which is convenient for allowing auto-generation of
/// the write function.
pub trait ArcBlobBase {
    /// Return the name of this blob
    fn blob_name() -> &'static str;
}

/// Supertype of [ArcBlob] that allows implementation of `compare` and `write`.
///
/// When defining an [ArcBlob] through the
/// [arc_blob!](crate::prelude::arc_blob) attribute macro without the
/// 'defaults' argument, you're required to implement this trait for
/// your type. This allows you to modify how comparison and writing
/// will happen.
pub trait ArcBlobImpl: ArcBlobBase + Send + Sync + Unpin {
    /// Compare two values, returning an Ordering.
    ///
    /// This is used from SWI-Prolog when sorting lists. The default
    /// implementation returns `Ordering::Equal`, effectively
    /// providing no sorting information.
    fn compare(&self, _other: &Self) -> Ordering {
        Ordering::Equal
    }

    /// Write a description of this ArcBlob.
    ///
    /// The given stream implements [Write](std::io::Write), and
    /// therefore can be used with the [write!](std::write!) macro.
    ///
    /// The normal way of implementing this is to print something like
    /// `"<blob_name ..blob_data..>"`. The default implementation
    /// simply prints `"<blob_name>"`.
    fn write(&self, stream: &mut PrologStream) -> io::Result<()> {
        write!(stream, "<{}>", Self::blob_name())
    }
}

/// A blob type whose data is shared with SWI-Prolog as an atomic
/// reference-counted pointer.
///
/// # Safety
/// This is unsafe because care has to be taken that the returned
/// `PL_blob_t` from `get_blob_definition` actually matches the blob
/// type.
pub unsafe trait ArcBlob: ArcBlobImpl {
    /// Return a blob definition for this ArcBlob.
    fn get_blob_definition() -> &'static fli::PL_blob_t;
}

/// Unify the term with the given `Arc`, using the given blob
/// definition to do so.
///
/// This is used from the arc blob macros.
///
/// # Safety
/// This is unsafe cause no attempt is made to ensure that the blob
/// definition matches the given data.
pub unsafe fn unify_with_arc<T>(
    term: &Term,
    blob_definition: &'static fli::PL_blob_t,
    arc: &Arc<T>,
) -> bool {
    term.assert_term_handling_possible();

    let result = fli::PL_unify_blob(
        term.term_ptr(),
        Arc::as_ptr(arc) as *mut c_void,
        0,
        blob_definition as *const fli::PL_blob_t as *mut fli::PL_blob_t,
    );

    result != 0
}

/// Unify the term with the given Cloneable, using the given blob
/// definition to do so.
///
/// This is used from the clone blob macros.
///
/// # Safety
/// This is unsafe cause no attempt is made to ensure that the blob
/// definition matches the given data.
pub unsafe fn unify_with_cloneable<T: Clone + Sized + Unpin>(
    term: &Term,
    blob_definition: &'static fli::PL_blob_t,
    val: &T,
) -> bool {
    term.assert_term_handling_possible();
    let cloned = val.clone();

    let result = fli::PL_unify_blob(
        term.term_ptr(),
        &cloned as *const T as *mut c_void,
        std::mem::size_of::<T>(),
        blob_definition as *const fli::PL_blob_t as *mut fli::PL_blob_t,
    );

    if result != 0 {
        std::mem::forget(cloned);
        true
    } else {
        false
    }
}

/// Retrieve an arc from the given term, using the given blob
/// definition.
///
/// This is used from the arc blob macros.
///
/// # Safety
/// This is unsafe cause no attempt is made to ensure that the blob
/// definition matches the given data.
pub unsafe fn get_arc_from_term<T>(
    term: &Term,
    blob_definition: &'static fli::PL_blob_t,
) -> Option<Arc<T>> {
    term.assert_term_handling_possible();

    let mut blob_type = std::ptr::null_mut();
    if fli::PL_is_blob(term.term_ptr(), &mut blob_type) == 0
        || blob_definition as *const fli::PL_blob_t != blob_type
    {
        return None;
    }

    let mut data: *mut T = std::ptr::null_mut();
    let result = fli::PL_get_blob(
        term.term_ptr(),
        &mut data as *mut *mut T as *mut *mut c_void,
        std::ptr::null_mut(),
        std::ptr::null_mut(),
    );

    if result == 0 {
        None
    } else {
        Arc::increment_strong_count(data);
        let arc = Arc::from_raw(data);
        Some(arc)
    }
}

/// Retrieve a cloneable value from the given term, using the given
/// blob definition.
///
/// This is used from the clone blob macros.
///
/// # Safety
/// This is unsafe cause no attempt is made to ensure that the blob
/// definition matches the given data.
pub unsafe fn get_cloned_from_term<T: Clone + Sized + Unpin>(
    term: &Term,
    blob_definition: &'static fli::PL_blob_t,
) -> Option<T> {
    term.assert_term_handling_possible();

    let mut blob_type = std::ptr::null_mut();
    if fli::PL_is_blob(term.term_ptr(), &mut blob_type) == 0
        || blob_definition as *const fli::PL_blob_t != blob_type
    {
        return None;
    }

    let mut data: *mut T = std::ptr::null_mut();
    let result = fli::PL_get_blob(
        term.term_ptr(),
        &mut data as *mut *mut T as *mut *mut c_void,
        std::ptr::null_mut(),
        std::ptr::null_mut(),
    );

    if result == 0 {
        None
    } else {
        let cloned = (*data).clone();
        Some(cloned)
    }
}

/// Put an arc into the given term, using the given blob definition.
///
/// This is used from the arc blob macros.
///
/// # Safety
/// This is unsafe cause no attempt is made to ensure that the blob
/// definition matches the given data.
pub unsafe fn put_arc_in_term<T>(
    term: &Term,
    blob_definition: &'static fli::PL_blob_t,
    arc: &Arc<T>,
) {
    term.assert_term_handling_possible();

    fli::PL_put_blob(
        term.term_ptr(),
        Arc::as_ptr(arc) as *mut c_void,
        0,
        blob_definition as *const fli::PL_blob_t as *mut fli::PL_blob_t,
    );
}

/// Put a Cloneable into the given term, using the given blob
/// definition.
///
/// This is used from the clone blob macros.
///
/// # Safety
/// This is unsafe cause no attempt is made to ensure that the blob
/// definition matches the given data.
pub unsafe fn put_cloneable_in_term<T: Clone + Sized + Unpin>(
    term: &Term,
    blob_definition: &'static fli::PL_blob_t,
    val: &T,
) {
    term.assert_term_handling_possible();

    let cloned = val.clone();

    fli::PL_put_blob(
        term.term_ptr(),
        &cloned as *const T as *mut c_void,
        std::mem::size_of::<T>(),
        blob_definition as *const fli::PL_blob_t as *mut fli::PL_blob_t,
    );

    std::mem::forget(cloned);
}

/// Increment the reference count on an Arc stored in a blob.
///
/// This is used from the arc blob macros.
///
/// # Safety
/// This is only safe to call from a thread with a swipl environment,
/// on an atom which contains an arc blob of the given type.
/// definition matches the given data.
pub unsafe fn acquire_arc_blob<T>(atom: fli::atom_t) {
    let data = fli::PL_blob_data(atom, std::ptr::null_mut(), std::ptr::null_mut()) as *const T;

    Arc::increment_strong_count(data);
}

/// Decrement the reference count on an Arc stored in a blob.
///
/// This is used from the arc blob macros.
///
/// # Safety
/// This is only safe to call from a thread with a swipl environment,
/// on an atom which contains an arc blob of the given type.
pub unsafe fn release_arc_blob<T>(atom: fli::atom_t) {
    let data = fli::PL_blob_data(atom, std::ptr::null_mut(), std::ptr::null_mut()) as *const T;

    Arc::decrement_strong_count(data);
}

/// Drop the rust value stored in a blob.
///
/// This is used from the clone blob macros.
///
/// # Safety
/// This is only safe to call from a thread with a swipl environment,
/// on an atom which contains a clone blob of the given type.
pub unsafe fn release_clone_blob<T>(atom: fli::atom_t) {
    let data =
        fli::PL_blob_data(atom, std::ptr::null_mut(), std::ptr::null_mut()) as *const T as *mut T;

    std::ptr::drop_in_place(data);
}

unsafe impl<T: ArcBlob> Unifiable for Arc<T> {
    fn unify(&self, term: &Term) -> bool {
        let blob_definition = T::get_blob_definition();
        unsafe { unify_with_arc(term, blob_definition, self) }
    }
}

unsafe impl<T: ArcBlob> TermGetable for Arc<T> {
    fn get(term: &Term) -> Option<Self> {
        let blob_definition = T::get_blob_definition();
        unsafe { get_arc_from_term(term, blob_definition) }
    }

    fn name() -> &'static str {
        T::blob_name()
    }
}

unsafe impl<T: ArcBlob> TermPutable for Arc<T> {
    fn put(&self, term: &Term) {
        let blob_definition = T::get_blob_definition();
        unsafe { put_arc_in_term(term, blob_definition, self) }
    }
}

/// Base type for [WrappedArcBlob].
///
/// This allows `blob_name` to be available to implementors of
/// [WrappedArcBlobImpl], which is convenient for allowing
/// auto-generation of the write function.
pub trait WrappedArcBlobBase {
    /// The type that the `WrappedArcBlob` is wrapping.
    type Inner: Send + Sync + Unpin;

    /// Return the name of this blob
    fn blob_name() -> &'static str;

    /// return a borrow to the wrapped Arc.
    fn get_arc(&self) -> &Arc<Self::Inner>;

    /// Create this wrapper from an Arc.
    fn from_arc(a: Arc<Self::Inner>) -> Self;
}

/// Supertype of [WrappedArcBlob] that allows implementation of
/// `compare` and `write`.
///
/// When defining a [WrappedArcBlob] through the
/// [wrapped_arc_blob!](crate::prelude::wrapped_arc_blob) macro
/// without the 'defaults' argument, you're required to implement this
/// trait for your type. This allows you to modify how comparison and
/// writing will happen.
pub trait WrappedArcBlobImpl: WrappedArcBlobBase {
    /// Compare two values, returning an Ordering.
    ///
    /// This is used from SWI-Prolog when sorting lists. The default
    /// implementation returns `Ordering::Equal`, effectively
    /// providing no sorting information.
    fn compare(_this: &Self::Inner, _other: &Self::Inner) -> Ordering {
        Ordering::Equal
    }

    /// Write a description of this WrappedArcBlob.
    ///
    /// The given stream implements [Write](std::io::Write), and
    /// therefore can be used with the [write!](std::write!) macro.
    ///
    /// The normal way of implementing this is to print something like
    /// `"<blob_name ..blob_data..>"`. The default implementation
    /// simply prints `"<blob_name>"`.
    fn write(_this: &Self::Inner, stream: &mut PrologStream) -> io::Result<()> {
        write!(stream, "<{}>", Self::blob_name())
    }
}

/// A blob type whose data is shared with SWI-Prolog as an atomic
/// reference-counted pointer, and which is wrapped into a wrapper
/// type.
///
/// # Safety
/// This is unsafe because care has to be taken that the returned
/// `PL_blob_t` from `get_blob_definition` actually matches the blob
/// type.
pub unsafe trait WrappedArcBlob: WrappedArcBlobImpl {
    /// Return a blob definition for this WrappedArcBlob.
    fn get_blob_definition() -> &'static fli::PL_blob_t;
}

/// Base type for [CloneBlob].
///
/// This allows `blob_name` to be available to implementors of
/// [CloneBlobImpl], which is convenient for allowing auto-generation of
/// the write function.
pub trait CloneBlobBase {
    fn blob_name() -> &'static str;
}

/// Supertype of [CloneBlob] that allows implementation of `compare`
/// and `write`.
///
/// When defining a [CloneBlob] through the
/// [clone_blob!](crate::prelude::clone_blob) attribute macro without the
/// 'defaults' argument, you're required to implement this trait for
/// your type. This allows you to modify how comparison and writing
/// will happen.
pub trait CloneBlobImpl: CloneBlobBase + Sized + Sync + Clone {
    /// Compare two values, returning an Ordering.
    ///
    /// This is used from SWI-Prolog when sorting lists. The default
    /// implementation returns `Ordering::Equal`, effectively
    /// providing no sorting information.
    fn compare(&self, _other: &Self) -> Ordering {
        Ordering::Equal
    }

    /// Write a description of this ArcBlob.
    ///
    /// The given stream implements [Write](std::io::Write), and
    /// therefore can be used with the [write!](std::write!) macro.
    ///
    /// The normal way of implementing this is to print something like
    /// `"<blob_name ..blob_data..>"`. The default implementation
    /// simply prints `"<blob_name>"`.
    fn write(&self, stream: &mut PrologStream) -> io::Result<()> {
        write!(stream, "<{}>", Self::blob_name())
    }
}

/// A blob type whose data is copied into SWI-Prolog and dropped on
/// garbage collection.
///
/// # Safety
/// This is unsafe because care has to be taken that the returned
/// `PL_blob_t` from `get_blob_definition` actually matches the blob
/// type.
pub unsafe trait CloneBlob: CloneBlobImpl {
    /// Return a blob definition for this CloneBlob.
    fn get_blob_definition() -> &'static fli::PL_blob_t;
}