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