1use crate::{
2 SECTION_HEADER_COMPACT_SIZE, SECTION_MAGIC, SectionHandle, SectionHeader, SectionStorage,
3 UnifiedLogStatus, UnifiedLogWrite,
4};
5use bincode::Encode;
6use bincode::config::standard;
7use bincode::enc::EncoderImpl;
8use bincode::enc::write::SizeWriter;
9use bincode::error::EncodeError;
10use cu29_traits::{CuResult, UnifiedLogType};
11
12#[derive(Debug, Default)]
13pub struct NoopSectionStorage {
14 bytes_written: usize,
15}
16
17impl SectionStorage for NoopSectionStorage {
18 fn initialize<E: Encode>(&mut self, header: &E) -> Result<usize, EncodeError> {
19 let header_size = encoded_size(header)?;
20 self.bytes_written = header_size;
21 Ok(header_size)
22 }
23
24 fn post_update_header<E: Encode>(&mut self, header: &E) -> Result<usize, EncodeError> {
25 encoded_size(header)
26 }
27
28 fn append<E: Encode>(&mut self, entry: &E) -> Result<usize, EncodeError> {
29 let size = encoded_size(entry)?;
30 self.bytes_written = self.bytes_written.saturating_add(size);
31 Ok(size)
32 }
33
34 fn flush(&mut self) -> CuResult<usize> {
35 Ok(self.bytes_written)
36 }
37}
38
39#[derive(Debug, Default)]
40pub struct NoopLogger {
41 total_used_space: usize,
42 total_allocated_space: usize,
43}
44
45impl NoopLogger {
46 pub fn new() -> Self {
47 Self::default()
48 }
49}
50
51impl UnifiedLogWrite<NoopSectionStorage> for NoopLogger {
52 fn add_section(
53 &mut self,
54 entry_type: UnifiedLogType,
55 requested_section_size: usize,
56 ) -> CuResult<SectionHandle<NoopSectionStorage>> {
57 let allocated_size = requested_section_size.max(SECTION_HEADER_COMPACT_SIZE as usize);
58 let section_header = SectionHeader {
59 magic: SECTION_MAGIC,
60 block_size: SECTION_HEADER_COMPACT_SIZE,
61 entry_type,
62 offset_to_next_section: allocated_size.min(u32::MAX as usize) as u32,
63 used: 0,
64 is_open: true,
65 };
66
67 self.total_allocated_space = self.total_allocated_space.saturating_add(allocated_size);
68 SectionHandle::create(section_header, NoopSectionStorage::default())
69 }
70
71 fn flush_section(&mut self, section: &mut SectionHandle<NoopSectionStorage>) {
72 section.mark_closed();
73 let _ = section.post_update_header();
74 if let Ok(used) = section.get_storage_mut().flush() {
75 self.total_used_space = self.total_used_space.saturating_add(used);
76 }
77 }
78
79 fn status(&self) -> UnifiedLogStatus {
80 UnifiedLogStatus {
81 total_used_space: self.total_used_space,
82 total_allocated_space: self.total_allocated_space,
83 }
84 }
85}
86
87fn encoded_size<E: Encode>(value: &E) -> Result<usize, EncodeError> {
88 let mut encoder = EncoderImpl::<_, _>::new(SizeWriter::default(), standard());
89 value.encode(&mut encoder)?;
90 Ok(encoder.into_writer().bytes_written)
91}