Skip to main content

nil_core/world/
savedata.rs

1// Copyright (C) Call of Nil contributors
2// SPDX-License-Identifier: AGPL-3.0-only
3
4use std::sync::Arc;
5
6use crate::error::{Error, Result};
7use crate::event::Emitter;
8use crate::savedata::Savedata;
9use crate::world::World;
10
11impl World {
12  pub(super) fn consume_pending_save(&mut self) -> Result<()> {
13    if let Some(handle) = self.save_handle.take() {
14      handle.save(self.to_bytes()?);
15    }
16
17    Ok(())
18  }
19
20  pub fn to_bytes(&self) -> Result<Vec<u8>> {
21    let mut buffer = Vec::new();
22    let data = Savedata::from(self);
23    data.write(&mut buffer)?;
24    Ok(buffer)
25  }
26}
27
28impl From<&World> for Savedata {
29  fn from(world: &World) -> Self {
30    let config = Arc::clone(&world.config);
31    Self {
32      round: world.round.to_idle(),
33      continent: world.continent.clone(),
34      player_manager: world.player_manager.clone(),
35      bot_manager: world.bot_manager.clone(),
36      precursor_manager: world.precursor_manager.clone(),
37      military: world.military.clone(),
38      ranking: world.ranking.clone(),
39      report: world.report.clone(),
40      config: Arc::unwrap_or_clone(config),
41      stats: world.stats.clone(),
42      chat: world.chat.clone(),
43    }
44  }
45}
46
47impl From<Savedata> for World {
48  fn from(savedata: Savedata) -> Self {
49    Self {
50      round: savedata.round,
51      continent: savedata.continent,
52      player_manager: savedata.player_manager,
53      bot_manager: savedata.bot_manager,
54      precursor_manager: savedata.precursor_manager,
55      military: savedata.military,
56      ranking: savedata.ranking,
57      report: savedata.report,
58      config: Arc::new(savedata.config),
59      stats: savedata.stats,
60      chat: savedata.chat,
61
62      emitter: Emitter::default(),
63      save_handle: None,
64      on_next_round: None,
65    }
66  }
67}
68
69impl TryFrom<&World> for Vec<u8> {
70  type Error = Error;
71
72  fn try_from(world: &World) -> Result<Self> {
73    world.to_bytes()
74  }
75}