r/rust • • 2d ago

🙋 seeking help & advice How can I protect a shared object from mutation ?

I have a config struct which I want to pass around to be read by several object. I want it to be written to by some objects like the save loader and debug stuff. What is the general way to achieve this in rust?

PS: It's a single threaded application

7 Upvotes

37 comments sorted by

48

u/dvogel 2d ago

Create two types. Each holds an Rc<RefCell<MyConfigStruct>>. One type exposes a read-only APi. The other a read-write API.

-21

u/Koltaia30 2d ago

I thought of this originally but it seems like I am creating my own solution instead of using the standard library

13

u/dobkeratops rustfind 2d ago

i'm not sure myself if the standard library has a solution to this. you may well need to write such a wrapper (or find a crate)

14

u/Cyan14 2d ago

For single thread, use Rc<RefCell<T>>. For multi thread, use Arc<RwLock<T>>

For read only, you can pass reference (&), Box<T>, Rc<T> or Arc<T>

Box, Rc, Arc are smart pointers, heap allocated. RefCell and RwLock / Mutex allows mutability even when you don't have a &mut reference, by using a runtime check.

1

u/Koltaia30 2d ago

How can I convert a Rc<RefCell<T>> to Rc<T> for the readers?

5

u/Cyan14 2d ago edited 2d ago

You can't do that. That's the whole point of having a runtime lock. You can do it, but the data inside will be a different copy (a deep clone) or you need to remove the cell, extract the inner data and wrap it in a new Rc.

You should be able to cheaply clone the Rc and pass the whole Rc<RefCell<T>> around and call read() on it wherever it's needed. Use the scoping in rust to drop the locks early.

your fn body {  
  {  // Scope to access cell }  
  // Lock dropped after inner scope  
}

1

u/Koltaia30 2d ago

3

u/Cyan14 2d ago

When will you write the config? If it's one time write, then you don't need to use a cell

Try LazyLock and OnceLock as well to see if that fits your needs

2

u/Koltaia30 2d ago

The config is made up of observable variables and it might change in runtime

1

u/OninDynamics 2d ago

How far into runtime? Like, will it be mutated after some other part of the code has read it, or will all mutations of it happen before it's read by anything else?

1

u/punk_dev 2d ago

One way I can think of is to wrap it in a struct, either a normal struct or a newtype. Don’t make inner field public.
Keep the mutating code inside the module, expose public read only methods.

2

u/zerosign0 2d ago

+1 This and I think you can also split the read and write traits so that the usage can be based on the trait of the wrapper of that struct that contains the Rc.

5

u/SplittyDev 2d ago

Simply give it to the read-only parts of the app as an immutable reference (&Config) instead of a mutable one (&mut Config).

2

u/Koltaia30 2d ago

I want to be stored by both sides

2

u/NullOfSpace 2d ago

To clarify, you have a shared object that you want to be able to write to from some references but not from others? Do you need to write to it after some locations already have immutable references, or is it enough to set up all of the mutable stuff first, then make it permanently immutable?

1

u/Koltaia30 2d ago

I need to change it after an immutable reference is stored. By immutable reference I mean mechanically immutable refernce not necesseraly a "&mut"

1

u/NullOfSpace 2d ago

In that case, you could make a wrapper struct around an Rc<RefCell<Config>> for your immutable refs that only exposes the immutable borrow method (maybe implement Deref or something) and clone the Rc to places where you need mutability.

5

u/coolmint859 2d ago

If you can design so that mutability happens once, and it's forever immutable, that could be much safer. But it depends on what the project is for.

1

u/edfloreshz 2d ago

For a single-threaded application, the usual solution is Rc<RefCell<T>>

2

u/Koltaia30 2d ago

How can I make it so that that those who shouldn't mutate it can't?

8

u/edfloreshz 2d ago

Use separate read-only and writable interfaces.

- For objects that should only read the configuration, pass a ConfigReader that exposes getter methods but doesn't provide access to the underlying data.
- For objects allowed to modify it, pass a ConfigWriter with specific setter methods.

Keep the actual Config and its RefCell private inside a config manager, rather than exposing an Rc<RefCell<Config>> to everyone.

1

u/mina86ng 2d ago edited 2d ago

Something like:

pub(crate::module::which::needs::write::access) struct Inner {
    pub some_option: SomeType,
    ...
}

pub struct Config(core::cell::RefCell<Inner>);

impl Config {
    pub fn some_option(&self) -> core::cell::Ref<'_, SomeType> {
        self.0.borrow().map(|inner| &inner.some_option)
    }
    ... same for all other options ...
    ... for options which are cheap to Copy, just copy the value ...

    pub(crate::module::which::needs::write::access)
    fn borrow_mut(&self) -> core::cell::RefMut<'_, Inner>{
        self.0.borrow_mut()
    }
}

(Obviously not tested, might need some tweaks).

Rc isn’t necessary, but depending on how patient you are with adding lifetime everywhere you may use it to simplify some code.

If you want to make it multithreaded, replace RefCell with RwLock or Mutex.

1

u/Koltaia30 2d ago

I see your point. So There should be a public reader interface and and an interface only in the scope of the writer. I like it but it seems it makes a lot of boilerplate necessary. I just want something that can be turned into somthing that can only access is immutably but still the same shared thing under it.

1

u/mina86ng 2d ago

You can do this:

pub struct ConfigData { ... }

pub struct Config(RefCell<ConfigData>);

impl Config {
    pub borrow(&self) -> ... { self.0.borrow() }
    pub(...) borrow_mut(&self) -> ... { self.0.borrow_mut() }
}

It removes boilerplate in the config definition but each reader must now go through borrow. If Rust’s Deref was nicer you could do impl Deref for Config { fn deref(&self) -> Ref<'_, ConfigData> { self.0.borrow() }, but unfortunately that’s not an option.

You can also remove some boilerplate with a macro:

macro_rules! cfg {
    (${ $name:ident: $typ:ty, }*) => {
        pub(...) struct InnerConfig { ${ pub $name: $typ, }* }
        impl Config {
            pub fn $name(&self) -> Ref<$typ> {
               self.0.borrow().map(|inner| &inner.$name)
            }
        }
    }
}

1

u/Koltaia30 2d ago

1

u/mina86ng 2d ago

Yeah, that works, but I don’t see what it gives you compared to what I wrote. It’s same code except using generic inner type. You would still need a way to borrow_mut of course. This isn’t to say there’s anything wrong with it, I just want to point out that using generic type likely won’t reduce amount of boilerplate (unless you use this pattern several times of course).

1

u/mina86ng 2d ago

By the way, keep in mind that with RefCell you must make sure you’re not holding the references to config options while part of the code modifying the config does the modifications. It may be beneficial to split the config into two parts:

pub(...) struct InnerConfig {
    pub some_mutable_option: SomeType,
    ...
}

struct Config {
    pub some_option: SomeType,
    pub(...) inner: RefCell<InnerConfig>,
}
```

`InnerConfig` may be split into multiple types as needed.  And depending what
you’re changing, another option might be to use `Cell` instead which would avoid
panics when trying to modify the value while it’s held r/o.

3

u/nick42d 2d ago

I feel like you could structure this differently. For example, of storing references inside your objects, are you able to give them immutable references only when they need it (e.g, to a function that responds to events or draws a ui frame?). Then you can mutate wherever the config is owned at any other time.

2

u/TrickAge2423 2d ago

What about left_right?

1

u/TrickAge2423 2d ago

Also, in STA, you can use cell as storage and Rc as snapshots:

struct Config(Cell<Rc<ConfigInner>>);

So in STA you just pop Rc, clone and put Rc back. To update, just replace Cell with new Rc.

1

u/coolmint859 2d ago edited 2d ago

Honestly I would consider the data flow of the config struct. It may be simpler and more robust to think of it as a pipeline, from creation to last usage.

If the config is meant to be read and written from indefinitely, consider inverting the usage so that some central owner (or the config itself) borrows the types that mutate the state of the config, and have the owner request the new data from them, rather than the writers accessing the config directly. It's much safer that way. (You can then wrap the inner values in Cell or RefCell so that you can borrow self immutably)

This also allows the readers to only need an Rc<T> or a simple & reference, since mutation is centralized.

0

u/ern0plus4 2d ago

Separate read-only data from read-write first.

0

u/AugustusLego 2d ago

Consider using an actor model. Sending a request over a broadcast channel, which contains a oneshot channel for the response