Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

С сырым указателем

// Copyright 2026 Google LLC
// SPDX-License-Identifier: Apache-2.0

#[derive(Debug)]
pub struct SelfReferentialBuffer {
    data: [u8; 1024],
    cursor: *mut u8,
}

impl SelfReferentialBuffer {
    pub fn new() -> Self {
        let mut buffer =
            SelfReferentialBuffer { data: [0; 1024], cursor: std::ptr::null_mut() };

        buffer.update_cursor();
        buffer
    }

    // Опасно: вызывать после каждого перемещения
    pub fn update_cursor(&mut self) {
        self.cursor = self.data.as_mut_ptr();
    }

    pub fn read(&self, n_bytes: usize) -> &[u8] {
        unsafe {
            let start = self.data.as_ptr();
            let end = start.add(1024);
            let cursor = self.cursor as *const u8;

            assert!((start..=end).contains(&cursor), "cursor is out of bounds");

            let available = end.offset_from(cursor) as usize;
            let len = n_bytes.min(available);
            std::slice::from_raw_parts(cursor, len)
        }
    }

    pub fn write(&mut self, bytes: &[u8]) {
        unsafe {
            let start = self.data.as_mut_ptr();
            let end = start.add(1024);

            assert!((start..=end).contains(&self.cursor), "cursor is out of bounds");
            let available = end.offset_from(self.cursor) as usize;
            let len = bytes.len().min(available);

            std::ptr::copy_nonoverlapping(bytes.as_ptr(), self.cursor, len);
            self.cursor = self.cursor.add(len);
        }
    }
}

Не тратьте здесь много времени.

Тезисы для обсуждения:

  • Подчеркните, что unsafe встречается часто. Это намёк на то, что другой дизайн может подойти лучше.
  • В блоках unsafe нет комментариев о безопасности. Поэтому этот код некорректен.
  • Блоки unsafe слишком широкие. Хорошая практика — использовать небольшие блоки unsafe с конкретным поведением, конкретными предусловиями и конкретными комментариями о безопасности.

Вопросы:

Вопрос: должны ли методы read() и write() быть помечены как unsafe? Ответ: да, потому что self.cursor будет нулевым указателем, пока в него что-то не записано.