safer-ring 0.0.1

A safe Rust wrapper around io_uring with zero-cost abstractions and compile-time memory safety guarantees
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
//! Safe ownership transfer operations (hot potato pattern) for the Ring.

use super::Ring;
use crate::error::{Result, SaferRingError};
use crate::ownership::OwnedBuffer;
use crate::safety::{SafeAcceptFuture, SafeOperation, SafeOperationFuture};
use std::io;
use std::os::unix::io::RawFd;
use std::sync::Arc;

impl<'ring> Ring<'ring> {
    /// Read with ownership transfer (hot potato pattern).
    ///
    /// You give the buffer, the kernel uses it, and you get it back when done.
    /// This is the core safe API pattern that prevents use-after-free bugs.
    ///
    /// # Arguments
    ///
    /// * `fd` - File descriptor to read from
    /// * `buffer` - Buffer to read into (ownership transferred)
    ///
    /// # Returns
    ///
    /// A future that resolves to `(bytes_read, buffer)` when the operation completes.
    /// The buffer is returned with the result, implementing the hot potato pattern.
    ///
    /// # Safety
    ///
    /// This method is completely safe. The buffer ownership is transferred to the
    /// kernel during the operation, preventing any use-after-free issues.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use safer_ring::{Ring, OwnedBuffer};
    ///
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let ring = Ring::new(32)?;
    /// let buffer = OwnedBuffer::new(1024);
    ///
    /// // Hot potato: give buffer, get it back
    /// let (bytes_read, buffer) = ring.read_owned(0, buffer).await?;
    /// println!("Read {} bytes", bytes_read);
    ///
    /// // Can reuse the same buffer
    /// let (bytes_read2, _buffer) = ring.read_owned(0, buffer).await?;
    /// println!("Read {} more bytes", bytes_read2);
    /// # Ok(())
    /// # }
    /// ```
    pub fn read_owned(&self, fd: RawFd, buffer: OwnedBuffer) -> SafeOperationFuture<'_> {
        // Generate unique submission ID
        let submission_id = {
            let mut tracker = self.orphan_tracker.lock().unwrap();
            tracker.next_submission_id()
        };

        // Submit the operation to the backend
        match self.submit_safe_read(fd, &buffer, submission_id) {
            Ok(_) => {
                // Create safe operation with ownership transfer
                let operation =
                    SafeOperation::new(buffer, submission_id, Arc::downgrade(&self.orphan_tracker));

                operation.into_future(self, self.waker_registry.clone())
            }
            Err(_e) => {
                // If submission fails, create a failed future
                SafeOperation::failed(buffer, submission_id, Arc::downgrade(&self.orphan_tracker))
                    .into_future(self, self.waker_registry.clone())
            }
        }
    }

    /// Write with ownership transfer (hot potato pattern).
    ///
    /// You give the buffer, the kernel uses it, and you get it back when done.
    /// This is the core safe API pattern that prevents use-after-free bugs.
    ///
    /// # Arguments
    ///
    /// * `fd` - File descriptor to write to
    /// * `buffer` - Buffer to write from (ownership transferred)
    ///
    /// # Returns
    ///
    /// A future that resolves to `(bytes_written, buffer)` when the operation completes.
    /// The buffer is returned with the result, implementing the hot potato pattern.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use safer_ring::{Ring, OwnedBuffer};
    ///
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let ring = Ring::new(32)?;
    /// let buffer = OwnedBuffer::from_slice(b"Hello, world!");
    ///
    /// // Hot potato: give buffer, get it back
    /// let (bytes_written, buffer) = ring.write_owned(1, buffer).await?;
    /// println!("Wrote {} bytes", bytes_written);
    /// # Ok(())
    /// # }
    /// ```
    pub fn write_owned(&self, fd: RawFd, buffer: OwnedBuffer) -> SafeOperationFuture<'_> {
        // Generate unique submission ID
        let submission_id = {
            let mut tracker = self.orphan_tracker.lock().unwrap();
            tracker.next_submission_id()
        };

        // Submit the operation to the backend
        match self.submit_safe_write(fd, &buffer, submission_id) {
            Ok(_) => {
                // Create safe operation with ownership transfer
                let operation =
                    SafeOperation::new(buffer, submission_id, Arc::downgrade(&self.orphan_tracker));

                operation.into_future(self, self.waker_registry.clone())
            }
            Err(_e) => {
                // If submission fails, create a failed future
                SafeOperation::failed(buffer, submission_id, Arc::downgrade(&self.orphan_tracker))
                    .into_future(self, self.waker_registry.clone())
            }
        }
    }

    /// Read with ownership transfer at a specific offset (hot potato pattern).
    ///
    /// This is the safe, recommended API for positioned file reads.
    /// You give the buffer, the kernel uses it at the specified offset,
    /// and you get it back when done.
    ///
    /// # Arguments
    ///
    /// * `fd` - File descriptor to read from
    /// * `buffer` - Buffer to read into (ownership transferred)
    /// * `offset` - Byte offset in the file to start reading from
    ///
    /// # Returns
    ///
    /// A future that resolves to `(bytes_read, buffer)` when the operation completes.
    /// The buffer is returned with the result, implementing the hot potato pattern.
    ///
    /// # Safety
    ///
    /// This method is completely safe. The buffer ownership is transferred to the
    /// kernel during the operation, preventing any use-after-free issues.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use safer_ring::{Ring, OwnedBuffer};
    ///
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let ring = Ring::new(32)?;
    /// let buffer = OwnedBuffer::new(1024);
    ///
    /// // Hot potato: give buffer, get it back
    /// let (bytes_read, buffer) = ring.read_at_owned(0, buffer, 100).await?;
    /// println!("Read {} bytes at offset 100", bytes_read);
    ///
    /// // Can reuse the same buffer for next read
    /// let (bytes_read2, _buffer) = ring.read_at_owned(0, buffer, 200).await?;
    /// println!("Read {} more bytes at offset 200", bytes_read2);
    /// # Ok(())
    /// # }
    /// ```
    pub fn read_at_owned(
        &self,
        fd: RawFd,
        buffer: OwnedBuffer,
        offset: u64,
    ) -> SafeOperationFuture<'_> {
        // Generate unique submission ID
        let submission_id = {
            let mut tracker = self.orphan_tracker.lock().unwrap();
            tracker.next_submission_id()
        };

        // Submit the operation to the backend
        match self.submit_safe_read_at(fd, &buffer, offset, submission_id) {
            Ok(_) => {
                // Create safe operation with ownership transfer
                let operation =
                    SafeOperation::new(buffer, submission_id, Arc::downgrade(&self.orphan_tracker));

                operation.into_future(self, self.waker_registry.clone())
            }
            Err(_e) => {
                // If submission fails, create a failed future
                SafeOperation::failed(buffer, submission_id, Arc::downgrade(&self.orphan_tracker))
                    .into_future(self, self.waker_registry.clone())
            }
        }
    }

    /// Write with ownership transfer at a specific offset (hot potato pattern).
    ///
    /// This is the safe, recommended API for positioned file writes.
    /// You give the buffer, the kernel uses it at the specified offset,
    /// and you get it back when done.
    ///
    /// # Arguments
    ///
    /// * `fd` - File descriptor to write to
    /// * `buffer` - Buffer to write from (ownership transferred)
    /// * `offset` - Byte offset in the file to start writing at
    /// * `len` - Number of bytes from the buffer to write
    ///
    /// # Returns
    ///
    /// A future that resolves to `(bytes_written, buffer)` when the operation completes.
    /// The buffer is returned with the result, implementing the hot potato pattern.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use safer_ring::{Ring, OwnedBuffer};
    ///
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let ring = Ring::new(32)?;
    /// let buffer = OwnedBuffer::from_slice(b"Hello, world!");
    ///
    /// // Hot potato: give buffer, get it back
    /// let (bytes_written, buffer) = ring.write_at_owned(1, buffer, 100, 13).await?;
    /// println!("Wrote {} bytes at offset 100", bytes_written);
    /// # Ok(())
    /// # }
    /// ```
    pub fn write_at_owned(
        &self,
        fd: RawFd,
        buffer: OwnedBuffer,
        offset: u64,
        len: usize,
    ) -> SafeOperationFuture<'_> {
        // Generate unique submission ID
        let submission_id = {
            let mut tracker = self.orphan_tracker.lock().unwrap();
            tracker.next_submission_id()
        };

        // Submit the operation to the backend
        match self.submit_safe_write_at(fd, &buffer, offset, len, submission_id) {
            Ok(_) => {
                // Create safe operation with ownership transfer
                let operation =
                    SafeOperation::new(buffer, submission_id, Arc::downgrade(&self.orphan_tracker));

                operation.into_future(self, self.waker_registry.clone())
            }
            Err(_e) => {
                // If submission fails, create a failed future
                SafeOperation::failed(buffer, submission_id, Arc::downgrade(&self.orphan_tracker))
                    .into_future(self, self.waker_registry.clone())
            }
        }
    }

    /// Accept connection with safe operation tracking.
    ///
    /// Unlike buffer operations, accept doesn't need buffer ownership transfer,
    /// but still uses the safe operation pattern for consistency.
    ///
    /// The completion (CQE) result for this operation contains the newly
    /// accepted client file descriptor. This method returns that fd.
    /// Note: the "bytes" field commonly used for read/write operations is not
    /// meaningful for accept and should not be interpreted as a byte count.
    ///
    /// # Arguments
    ///
    /// * `fd` - Listening socket file descriptor
    ///
    /// # Returns
    ///
    /// A future that resolves to the accepted client file descriptor.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use safer_ring::Ring;
    ///
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let ring = Ring::new(32)?;
    /// let listening_fd = 3; // Assume we have a listening socket
    ///
    /// let client_fd = ring.accept_safe(listening_fd).await?;
    /// println!("Accepted client on fd {}", client_fd);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn accept_safe(&self, fd: RawFd) -> Result<RawFd> {
        // Generate unique submission ID
        let submission_id = {
            let mut tracker = self.orphan_tracker.lock().unwrap();
            tracker.next_submission_id()
        };

        // Create a buffer for the accept operation (for sockaddr info)
        let buffer = OwnedBuffer::new(256); // Large enough for sockaddr structures

        // Create a SafeOperation for the accept
        let operation =
            SafeOperation::new(buffer, submission_id, Arc::downgrade(&self.orphan_tracker));

        // Submit the accept operation to the backend
        {
            let (buffer_ptr, buffer_size) = operation.buffer_info()?;
            let mut backend = self.backend.borrow_mut();
            backend.submit_operation(
                crate::operation::OperationType::Accept,
                fd,
                0, // offset not used for accept
                buffer_ptr,
                buffer_size,
                submission_id,
            )?;
        }

        // Create future to poll for completion
        let future = SafeAcceptFuture::new(operation, self, self.waker_registry.clone());

        // Await the accept completion. For accept, the CQE result is the new fd.
        let (accepted_fd, _buffer) = future.await?;

        // Return the newly accepted socket fd from the kernel.
        Ok(accepted_fd as RawFd)
    }

    /// Get ring-managed buffer for operations.
    ///
    /// This provides a buffer from the ring's internal pool, eliminating
    /// the need for users to manage buffer allocation and ownership.
    ///
    /// # Arguments
    ///
    /// * `size` - Size of buffer to allocate
    ///
    /// # Returns
    ///
    /// A buffer owned by the ring that can be used in operations.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use safer_ring::Ring;
    ///
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let ring = Ring::new(32)?;
    ///
    /// // Ring provides the buffer
    /// let buffer = ring.get_buffer(4096)?;
    /// let (bytes_read, buffer) = ring.read_owned(0, buffer).await?;
    /// println!("Read {} bytes using ring buffer", bytes_read);
    /// # Ok(())
    /// # }
    /// ```
    pub fn get_buffer(&self, size: usize) -> Result<OwnedBuffer> {
        // In a real implementation, this would use a buffer pool
        // For now, just create a new buffer
        Ok(OwnedBuffer::new(size))
    }

    /// Submit a safe read operation to the backend.
    ///
    /// This method submits the read operation directly to the backend using
    /// the buffer's raw pointer, since we have ownership transfer semantics.
    fn submit_safe_read(&self, fd: RawFd, buffer: &OwnedBuffer, submission_id: u64) -> Result<()> {
        let (buffer_ptr, buffer_len) = buffer.as_ptr_and_len();

        self.backend.borrow_mut().submit_operation(
            crate::operation::OperationType::Read,
            fd,
            0, // offset 0 for simple reads
            buffer_ptr,
            buffer_len,
            submission_id,
        )
    }

    /// Submit a safe write operation to the backend.
    ///
    /// This method submits the write operation directly to the backend using
    /// the buffer's raw pointer, since we have ownership transfer semantics.
    fn submit_safe_write(&self, fd: RawFd, buffer: &OwnedBuffer, submission_id: u64) -> Result<()> {
        let (buffer_ptr, buffer_len) = buffer.as_ptr_and_len();

        self.backend.borrow_mut().submit_operation(
            crate::operation::OperationType::Write,
            fd,
            0, // offset 0 for simple writes
            buffer_ptr,
            buffer_len,
            submission_id,
        )
    }

    /// Submit a safe read operation with an offset to the backend.
    ///
    /// This method submits the read operation directly to the backend using
    /// the buffer's raw pointer, since we have ownership transfer semantics.
    fn submit_safe_read_at(
        &self,
        fd: RawFd,
        buffer: &OwnedBuffer,
        offset: u64,
        submission_id: u64,
    ) -> Result<()> {
        let (buffer_ptr, buffer_len) = buffer.as_ptr_and_len();

        self.backend.borrow_mut().submit_operation(
            crate::operation::OperationType::Read,
            fd,
            offset, // Pass the offset
            buffer_ptr,
            buffer_len,
            submission_id,
        )
    }

    /// Submit a safe write operation with an offset to the backend.
    ///
    /// This method submits the write operation directly to the backend using
    /// the buffer's raw pointer, since we have ownership transfer semantics.
    fn submit_safe_write_at(
        &self,
        fd: RawFd,
        buffer: &OwnedBuffer,
        offset: u64,
        len: usize,
        submission_id: u64,
    ) -> Result<()> {
        let (buffer_ptr, buffer_capacity) = buffer.as_ptr_and_len();
        if len > buffer_capacity {
            return Err(SaferRingError::Io(io::Error::new(
                io::ErrorKind::InvalidInput,
                "Length to write exceeds buffer capacity",
            )));
        }

        self.backend.borrow_mut().submit_operation(
            crate::operation::OperationType::Write,
            fd,
            offset, // Pass the offset
            buffer_ptr,
            len, // Pass the specific length to write
            submission_id,
        )
    }
}