scuffle 0.1.0

High-level bindings to libscf on illumos
Documentation
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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

use crate::PropertyGroup;
use crate::PropertyGroupDirect;
use crate::Scf;
use crate::ValueKind;
use crate::ValueRef;
use crate::error::LibscfError;
use crate::error::ScfEntityDescription;
use crate::error::ToEntityDescription;
use crate::error::TransactionBuildError;
use crate::error::TransactionCommitError;
use crate::error::TransactionOp;
use crate::error::TransactionPropertyError;
use crate::scf::ScfObject;
use crate::utf8cstring::Utf8CString;
use crate::value::ScfValue;
use std::marker::PhantomData;

/// Type-state marker for a [`Transaction`] in the reset (initial) state.
///
/// Reset transactions must be started via [`Transaction::start()`].
#[derive(Debug)]
pub enum TransactionReset {}

/// Type-state marker for a [`Transaction`] in the started state.
///
/// Started transactions may have entries added to modify properties, may be
/// reset, and may be committed.
#[derive(Debug)]
pub enum TransactionStarted {}

/// Type-state marker for a [`Transaction`] in the committed state.
///
/// Committed transactions can only be dropped or reset.
#[derive(Debug)]
pub enum TransactionCommitted {}

/// Result of committing a [`Transaction`].
#[derive(Debug)]
pub enum TransactionCommitResult<'a, 'pg> {
    /// Commit succeeded.
    Success(Transaction<'a, 'pg, TransactionCommitted>),

    /// Commit failed because the transaction was out of date.
    ///
    /// The associated [`Transaction`] has already been reset; it can be started
    /// again to retry the change.
    OutOfDate(Transaction<'a, 'pg, TransactionReset>),
}

/// Transaction for modifying properties within a [`PropertyGroup`].
///
/// [`Transaction`] uses a type-state pattern where methods are only available
/// in particular states. The lifecycle of a `Transaction` is:
///
/// 1. Begin in the [`TransactionReset`] state
/// 2. Call [`Transaction::start()`] to begin the transaction, transitioning to
///    the [`TransactionStarted`] state.
/// 3. Call any number of methods to delete, add, or change properties. A given
///    property may only have one entry in a single transaction.
/// 4. Either call [`Transaction::reset()`] (return to 1) or
///    [`Transaction::commit()`] to commit the transaction. On success,
///    transitions to the terminal [`TransactionCommitted`] state; on "out of
///    date" (i.e., the property group was concurrently modified), transitions
///    back to the reset state (1).
#[derive(Debug)]
pub struct Transaction<'a, 'pg, St> {
    // All the real guts of a transaction is held in `TransactionInner` which
    // does _not_ have the `St` type-state (allowing us to change the type state
    // by moving `inner` around).
    inner: TransactionInner<'a, 'pg>,
    _state: PhantomData<fn() -> St>,
}

#[derive(Debug)]
struct TransactionInner<'a, 'pg> {
    // Parent property group of this transaction.
    property_group: &'a mut PropertyGroup<'pg, PropertyGroupDirect>,
    handle: ScfObject<'a, libscf_sys::scf_transaction_t>,
    // We don't want to drop the `TransactionEntry` values as long as they're
    // still associated with the transaction in `handle`. We clear `entries` out
    // whenever we `reset()`.
    entries: Vec<TransactionEntry<'a>>,
}

impl Drop for TransactionInner<'_, '_> {
    fn drop(&mut self) {
        // reset the transaction to detach any entries before dropping (and
        // therefore destroying) the transaction itself
        self.reset();
    }
}

impl TransactionInner<'_, '_> {
    fn reset(&mut self) {
        // Reset the transaction...
        () = unsafe {
            libscf_sys::scf_transaction_reset(self.handle.as_mut_ptr())
        };

        // then drop (and destroy) all the entries that were associated with it.
        self.entries.clear();
    }
}

// Methods available on transaction in any state.
impl<'a, 'pg, St> Transaction<'a, 'pg, St> {
    /// Reset the transaction, clearing any pending entries.
    pub fn reset(mut self) -> Transaction<'a, 'pg, TransactionReset> {
        self.inner.reset();
        Transaction { inner: self.inner, _state: PhantomData }
    }

    /// Returns true if this transaction has no entries.
    pub fn is_empty(&self) -> bool {
        self.inner.entries.is_empty()
    }

    fn scf(&self) -> &'a Scf<'a> {
        self.inner.property_group.scf()
    }

    fn pg_entity_description(&self) -> ScfEntityDescription {
        self.inner.property_group.to_entity_description()
    }
}

// Methods available on Reset (also the just-created state) transactions.
impl<'a, 'pg> Transaction<'a, 'pg, TransactionReset> {
    pub(crate) fn new(
        property_group: &'a mut PropertyGroup<'pg, PropertyGroupDirect>,
    ) -> Result<Self, TransactionBuildError> {
        let handle = property_group.scf().scf_transaction_create()?;
        Ok(Self {
            inner: TransactionInner {
                property_group,
                handle,
                entries: Vec::new(),
            },
            _state: PhantomData,
        })
    }

    /// Start the transaction.
    ///
    /// Committing a transaction will return
    /// [`TransactionCommitResult::OutOfDate`] if the property group is modified
    /// between `start()` and `commit()`.
    pub fn start(
        mut self,
    ) -> Result<Transaction<'a, 'pg, TransactionStarted>, TransactionBuildError>
    {
        match unsafe {
            self.inner
                .property_group
                .scf_transaction_start(self.inner.handle.as_mut_ptr())
        } {
            Ok(()) => {
                Ok(Transaction { inner: self.inner, _state: PhantomData })
            }
            Err(err) => Err(TransactionBuildError::Start {
                property_group: self.pg_entity_description(),
                err,
            }),
        }
    }
}

// Methods available on Started transactions.
impl<'a, 'pg> Transaction<'a, 'pg, TransactionStarted> {
    fn check_property_name(
        &self,
        name: &str,
    ) -> Result<Utf8CString, TransactionBuildError> {
        Utf8CString::from_str(name).map_err(|err| {
            TransactionBuildError::InvalidName {
                property_group: self.pg_entity_description(),
                err,
            }
        })
    }

    fn collect_values<'b, I: IntoIterator<Item = ValueRef<'b>>>(
        &self,
        name: &Utf8CString,
        expected_kind: ValueKind,
        values: I,
    ) -> Result<Vec<ScfValue<'a>>, TransactionBuildError> {
        let mut collected = Vec::new();
        for val in values {
            if val.kind() != expected_kind {
                return Err(TransactionBuildError::TypeMismatch {
                    property_group: self.pg_entity_description(),
                    name: name.to_string().into_boxed_str(),
                    property_type: expected_kind,
                    value_type: val.kind(),
                });
            }

            let mut scf_val = ScfValue::new(self.scf())?;
            scf_val.set(val).map_err(|err| {
                TransactionBuildError::SetValue {
                    property_group: self.pg_entity_description(),
                    name: name.to_string().into_boxed_str(),
                    err,
                }
            })?;

            collected.push(scf_val);
        }
        Ok(collected)
    }

    /// Delete a property by name.
    pub fn property_delete(
        &mut self,
        name: &str,
    ) -> Result<(), TransactionBuildError> {
        let name = self.check_property_name(name)?;
        let entry = TransactionEntry::new_delete(self, &name)?;
        self.inner.entries.push(entry);
        Ok(())
    }

    /// Add a new property with a single value.
    ///
    /// # Errors
    ///
    /// This method will fail if the property already exists. Consider
    /// [`Transaction::property_ensure()`] for "add or update" semantics.
    pub fn property_new(
        &mut self,
        name: &str,
        value: ValueRef<'_>,
    ) -> Result<(), TransactionBuildError> {
        self.property_new_multiple(name, value.kind(), std::iter::once(value))
    }

    /// Add a new property with the given values.
    ///
    /// # Errors
    ///
    /// This method will fail if the property already exists or if any element
    /// of `values` has a kind inconsistent with `value_kind`. Consider
    /// [`Transaction::property_ensure_multiple()`] for "add or update"
    /// semantics.
    pub fn property_new_multiple<'b, I>(
        &mut self,
        name: &str,
        value_kind: ValueKind,
        values: I,
    ) -> Result<(), TransactionBuildError>
    where
        I: IntoIterator<Item = ValueRef<'b>>,
    {
        let name = self.check_property_name(name)?;
        let values = self.collect_values(&name, value_kind, values)?;
        let entry = TransactionEntry::new_new(self, &name, value_kind, values)?;
        self.inner.entries.push(entry);
        Ok(())
    }

    /// Change an existing property to have a single value.
    ///
    /// # Errors
    ///
    /// This method will fail if the property does not exist or if the type of
    /// `value` is not consistent with the existing property value(s). Consider
    /// [`Transaction::property_ensure()`] for "add or update" semantics.
    pub fn property_change(
        &mut self,
        name: &str,
        value: ValueRef<'_>,
    ) -> Result<(), TransactionBuildError> {
        self.property_change_multiple(
            name,
            value.kind(),
            std::iter::once(value),
        )
    }

    /// Change an existing property to have the given values.
    ///
    /// # Errors
    ///
    /// This method will fail if the property does not exist, if any element
    /// of `values` has a kind inconsistent with `value_kind`, or if
    /// `value_kind` is not consistent with the existing property value(s).
    /// Consider [`Transaction::property_ensure_multiple()`] for "add or update"
    /// semantics.
    pub fn property_change_multiple<'b, I>(
        &mut self,
        name: &str,
        value_kind: ValueKind,
        values: I,
    ) -> Result<(), TransactionBuildError>
    where
        I: IntoIterator<Item = ValueRef<'b>>,
    {
        let name = self.check_property_name(name)?;
        let values = self.collect_values(&name, value_kind, values)?;
        let entry =
            TransactionEntry::new_change(self, &name, value_kind, values)?;
        self.inner.entries.push(entry);
        Ok(())
    }

    /// Change an existing property to have a single value, changing its type if
    /// necessary.
    ///
    /// # Errors
    ///
    /// This method will fail if the property does not exist. Consider
    /// [`Transaction::property_ensure()`] for "add or update" semantics.
    pub fn property_change_type(
        &mut self,
        name: &str,
        value: ValueRef<'_>,
    ) -> Result<(), TransactionBuildError> {
        self.property_change_type_multiple(
            name,
            value.kind(),
            std::iter::once(value),
        )
    }

    /// Change an existing property to have the given values, changing its type
    /// if necessary.
    ///
    /// # Errors
    ///
    /// This method will fail if the property does not exist or if any element
    /// of `values` has a kind inconsistent with `value_kind`. Consider
    /// [`Transaction::property_ensure_multiple()`] for "add or update"
    /// semantics.
    pub fn property_change_type_multiple<'b, I>(
        &mut self,
        name: &str,
        value_kind: ValueKind,
        values: I,
    ) -> Result<(), TransactionBuildError>
    where
        I: IntoIterator<Item = ValueRef<'b>>,
    {
        let name = self.check_property_name(name)?;
        let values = self.collect_values(&name, value_kind, values)?;
        let entry =
            TransactionEntry::new_change_type(self, &name, value_kind, values)?;
        self.inner.entries.push(entry);
        Ok(())
    }

    /// Ensure a property exists with the given single value.
    ///
    /// This method will create the property if it does not exist, and will
    /// change its value (and type if necessary) if it does.
    pub fn property_ensure(
        &mut self,
        name: &str,
        value: ValueRef<'_>,
    ) -> Result<(), TransactionBuildError> {
        self.property_ensure_multiple(
            name,
            value.kind(),
            std::iter::once(value),
        )
    }

    /// Ensure a property exists with the given values.
    ///
    /// This method will create the property if it does not exist, and will
    /// change its values (and type if necessary) if it does.
    ///
    /// # Errors
    ///
    /// Fails if any element of `values` has a kind inconsistent with
    /// `value_kind`.
    pub fn property_ensure_multiple<'b, I>(
        &mut self,
        name: &str,
        value_kind: ValueKind,
        values: I,
    ) -> Result<(), TransactionBuildError>
    where
        I: IntoIterator<Item = ValueRef<'b>>,
    {
        let already_exists = self
            .inner
            .property_group
            .property(name)
            .map_err(|err| TransactionBuildError::ExistenceLookup {
                property_group: self.pg_entity_description(),
                name: name.to_string().into_boxed_str(),
                err,
            })?
            .is_some();

        if already_exists {
            self.property_change_type_multiple(name, value_kind, values)
        } else {
            self.property_new_multiple(name, value_kind, values)
        }
    }

    /// Commit this transaction.
    pub fn commit(
        mut self,
    ) -> Result<TransactionCommitResult<'a, 'pg>, TransactionCommitError> {
        match unsafe {
            libscf_sys::scf_transaction_commit(self.inner.handle.as_mut_ptr())
        } {
            0 => Ok(TransactionCommitResult::OutOfDate(self.reset())),
            1 => Ok(TransactionCommitResult::Success(Transaction {
                inner: self.inner,
                _state: PhantomData,
            })),
            _ => {
                let err = LibscfError::last();
                Err(TransactionCommitError {
                    property_group: self.pg_entity_description(),
                    err,
                })
            }
        }
    }
}

#[derive(Debug)]
struct TransactionEntry<'a> {
    handle: ScfObject<'a, libscf_sys::scf_transaction_entry_t>,
    // We never use these, but have to keep them from being destroyed as long as
    // they're associated with `handle`.
    _values: Vec<ScfValue<'a>>,
}

impl Drop for TransactionEntry<'_> {
    fn drop(&mut self) {
        // Before dropping the handle and kind, which will destroy both the
        // entry and any associated values, detach the values from the entry.
        unsafe { libscf_sys::scf_entry_reset(self.handle.as_mut_ptr()) };
    }
}

impl<'a> TransactionEntry<'a> {
    fn new_common<F>(
        tx: &mut Transaction<'a, '_, TransactionStarted>,
        name: &Utf8CString,
        mut values: Vec<ScfValue<'a>>,
        f: F,
    ) -> Result<Self, TransactionBuildError>
    where
        F: FnOnce(
            &mut Transaction<'a, '_, TransactionStarted>,
            &Utf8CString,
            &mut ScfObject<'a, libscf_sys::scf_transaction_entry_t>,
        ) -> Result<(), TransactionBuildError>,
    {
        let mut handle = tx.scf().scf_entry_create()?;

        f(tx, name, &mut handle)?;

        for val in &mut values {
            unsafe { val.scf_add_to_transaction_entry(handle.as_mut_ptr()) }
                .map_err(|err| TransactionPropertyError {
                    property_group: tx.pg_entity_description(),
                    name: name.to_string().into_boxed_str(),
                    op: TransactionOp::AddValue,
                    err,
                })?;
        }

        Ok(Self { handle, _values: values })
    }

    fn new_delete(
        tx: &mut Transaction<'a, '_, TransactionStarted>,
        name: &Utf8CString,
    ) -> Result<Self, TransactionBuildError> {
        let values = Vec::new(); // delete has no attached values

        Self::new_common(tx, name, values, |tx, name, handle| {
            LibscfError::from_ret(unsafe {
                libscf_sys::scf_transaction_property_delete(
                    tx.inner.handle.as_mut_ptr(),
                    handle.as_mut_ptr(),
                    name.as_c_str().as_ptr(),
                )
            })
            .map_err(|err| TransactionPropertyError {
                property_group: tx.pg_entity_description(),
                name: name.to_string().into_boxed_str(),
                op: TransactionOp::Delete,
                err,
            })?;
            Ok(())
        })
    }

    fn new_new(
        tx: &mut Transaction<'a, '_, TransactionStarted>,
        name: &Utf8CString,
        value_kind: ValueKind,
        values: Vec<ScfValue<'a>>,
    ) -> Result<Self, TransactionBuildError> {
        Self::new_common(tx, name, values, |tx, name, handle| {
            LibscfError::from_ret(unsafe {
                libscf_sys::scf_transaction_property_new(
                    tx.inner.handle.as_mut_ptr(),
                    handle.as_mut_ptr(),
                    name.as_c_str().as_ptr(),
                    value_kind.to_scf_type(),
                )
            })
            .map_err(|err| TransactionPropertyError {
                property_group: tx.pg_entity_description(),
                name: name.to_string().into_boxed_str(),
                op: TransactionOp::New,
                err,
            })?;
            Ok(())
        })
    }

    fn new_change(
        tx: &mut Transaction<'a, '_, TransactionStarted>,
        name: &Utf8CString,
        value_kind: ValueKind,
        values: Vec<ScfValue<'a>>,
    ) -> Result<Self, TransactionBuildError> {
        Self::new_common(tx, name, values, |tx, name, handle| {
            LibscfError::from_ret(unsafe {
                libscf_sys::scf_transaction_property_change(
                    tx.inner.handle.as_mut_ptr(),
                    handle.as_mut_ptr(),
                    name.as_c_str().as_ptr(),
                    value_kind.to_scf_type(),
                )
            })
            .map_err(|err| TransactionPropertyError {
                property_group: tx.pg_entity_description(),
                name: name.to_string().into_boxed_str(),
                op: TransactionOp::Change,
                err,
            })?;
            Ok(())
        })
    }

    fn new_change_type(
        tx: &mut Transaction<'a, '_, TransactionStarted>,
        name: &Utf8CString,
        value_kind: ValueKind,
        values: Vec<ScfValue<'a>>,
    ) -> Result<Self, TransactionBuildError> {
        Self::new_common(tx, name, values, |tx, name, handle| {
            LibscfError::from_ret(unsafe {
                libscf_sys::scf_transaction_property_change_type(
                    tx.inner.handle.as_mut_ptr(),
                    handle.as_mut_ptr(),
                    name.as_c_str().as_ptr(),
                    value_kind.to_scf_type(),
                )
            })
            .map_err(|err| TransactionPropertyError {
                property_group: tx.pg_entity_description(),
                name: name.to_string().into_boxed_str(),
                op: TransactionOp::ChangeType,
                err,
            })?;
            Ok(())
        })
    }
}