Movatterモバイル変換


[0]ホーム

URL:


Docs.rs

Cratebytes

Source
Expand description

Provides abstractions for working with bytes.

Thebytes crate provides an efficient byte buffer structure(Bytes) and traits for working with bufferimplementations (Buf,BufMut).

§Bytes

Bytes is an efficient container for storing and operating on contiguousslices of memory. It is intended for use primarily in networking code, butcould have applications elsewhere as well.

Bytes values facilitate zero-copy network programming by allowing multipleBytes objects to point to the same underlying memory. This is managed byusing a reference count to track when the memory is no longer needed and canbe freed.

ABytes handle can be created directly from an existing byte store (such as&[u8]orVec<u8>), but usually aBytesMut is used first and written to. Forexample:

usebytes::{BytesMut, BufMut};letmutbuf = BytesMut::with_capacity(1024);buf.put(&b"hello world"[..]);buf.put_u16(1234);leta = buf.split();assert_eq!(a,b"hello world\x04\xD2"[..]);buf.put(&b"goodbye world"[..]);letb = buf.split();assert_eq!(b,b"goodbye world"[..]);assert_eq!(buf.capacity(),998);

In the above example, only a single buffer of 1024 is allocated. The handlesa andb will share the underlying buffer and maintain indices trackingthe view into the buffer represented by the handle.

See thestruct docs for more details.

§Buf,BufMut

These two traits provide read and write access to buffers. The underlyingstorage may or may not be in contiguous memory. For example,Bytes is abuffer that guarantees contiguous memory, but arope stores the bytes indisjoint chunks.Buf andBufMut maintain cursors tracking the currentposition in the underlying byte storage. When bytes are read or written, thecursor is advanced.

§Relation withRead andWrite

At first glance, it may seem thatBuf andBufMut overlap infunctionality withstd::io::Read andstd::io::Write. However, theyserve different purposes. A buffer is the value that is provided as anargument toRead::read andWrite::write.Read andWrite may thenperform a syscall, which has the potential of failing. Operations onBufandBufMut are infallible.

Re-exports§

pub use crate::buf::Buf;
pub use crate::buf::BufMut;

Modules§

buf
Utilities for working with buffers.

Structs§

Bytes
A cheaply cloneable and sliceable chunk of contiguous memory.
BytesMut
A unique reference to a contiguous slice of memory.
TryGetError
Error type for thetry_get_ methods ofBuf.Indicates that there were not enough remainingbytes in the buffer while attemptingto get a value from aBuf with oneof thetry_get_ methods.

[8]ページ先頭

©2009-2025 Movatter.jp