view rust/hg-core/src/dirstate_tree/owning.rs @ 49000:dd6b67d5c256 stable

rust: fix unsound `OwningDirstateMap` As per the previous patch, `OwningDirstateMap` is unsound. Self-referential structs are difficult to implement correctly in Rust since the compiler is free to move structs around as much as it wants to. They are also very rarely needed in practice, so the state-of-the-art on how they should be done within the Rust rules is still a bit new. The crate `ouroboros` is an attempt at providing a safe way (in the Rust sense) of declaring self-referential structs. It is getting a lot attention and was improved very quickly when soundness issues were found in the past: rather than relying on our own (limited) review circle, we might as well use the de-facto common crate to fix this problem. This will give us a much better chance of finding issues should any new ones be discovered as well as the benefit of fewer `unsafe` APIs of our own. I was starting to think about how I would present a safe API to the old struct but soon realized that the callback-based approach was already done in `ouroboros`, along with a lot more care towards refusing incorrect structs. In short: we don't return a mutable reference to the `DirstateMap` anymore, we expect users of its API to pass a `FnOnce` that takes the map as an argument. This allows our `OwningDirstateMap` to control the input and output lifetimes of the code that modifies it to prevent such issues. Changing to `ouroboros` meant changing every API with it, but it is relatively low churn in the end. It correctly identified the example buggy modification of `copy_map_insert` outlined in the previous patch as violating the borrow rules. Differential Revision: https://phab.mercurial-scm.org/D12429
author Raphaël Gomès <rgomes@octobus.net>
date Tue, 05 Apr 2022 10:55:28 +0200
parents cfd270d83169
children 6cce0afc1454 e98fd81bb151
line wrap: on
line source

use crate::{DirstateError, DirstateParents};

use super::dirstate_map::DirstateMap;
use std::ops::Deref;

use ouroboros::self_referencing;

/// Keep a `DirstateMap<'on_disk>` next to the `on_disk` buffer that it
/// borrows.
#[self_referencing]
pub struct OwningDirstateMap {
    on_disk: Box<dyn Deref<Target = [u8]> + Send>,
    #[borrows(on_disk)]
    #[covariant]
    map: DirstateMap<'this>,
}

impl OwningDirstateMap {
    pub fn new_empty<OnDisk>(on_disk: OnDisk) -> Self
    where
        OnDisk: Deref<Target = [u8]> + Send + 'static,
    {
        let on_disk = Box::new(on_disk);

        OwningDirstateMapBuilder {
            on_disk,
            map_builder: |bytes| DirstateMap::empty(&bytes),
        }
        .build()
    }

    pub fn new_v1<OnDisk>(
        on_disk: OnDisk,
    ) -> Result<(Self, DirstateParents), DirstateError>
    where
        OnDisk: Deref<Target = [u8]> + Send + 'static,
    {
        let on_disk = Box::new(on_disk);
        let mut parents = DirstateParents::NULL;

        Ok((
            OwningDirstateMapTryBuilder {
                on_disk,
                map_builder: |bytes| {
                    DirstateMap::new_v1(&bytes).map(|(dmap, p)| {
                        parents = p.unwrap_or(DirstateParents::NULL);
                        dmap
                    })
                },
            }
            .try_build()?,
            parents,
        ))
    }

    pub fn new_v2<OnDisk>(
        on_disk: OnDisk,
        data_size: usize,
        metadata: &[u8],
    ) -> Result<Self, DirstateError>
    where
        OnDisk: Deref<Target = [u8]> + Send + 'static,
    {
        let on_disk = Box::new(on_disk);

        OwningDirstateMapTryBuilder {
            on_disk,
            map_builder: |bytes| {
                DirstateMap::new_v2(&bytes, data_size, metadata)
            },
        }
        .try_build()
    }

    pub fn with_dmap_mut<R>(
        &mut self,
        f: impl FnOnce(&mut DirstateMap) -> R,
    ) -> R {
        self.with_map_mut(f)
    }

    pub fn get_map(&self) -> &DirstateMap {
        self.borrow_map()
    }

    pub fn on_disk(&self) -> &[u8] {
        self.borrow_on_disk()
    }
}