27 KiB
API Reference
Complete API reference for the P2P file sharing library. This documentation covers all public APIs, types, and functions.
Table of Contents
Module Import Guide
The library uses a module-based import system. Import modules as follows:
const core = @import("core");
const network = @import("network");
const protocol = @import("protocol");
const files = @import("files");
const p2p = @import("p2p");
Core Module
The core module provides fundamental types and utilities for P2P networking including error handling, address management, buffer operations, socket I/O, and connection management.
address.zig - Network Address Management
Types
pub const AddressFamily = enum(u8) {
ipv4 = 1,
ipv6 = 2,
unix = 3,
custom = 4,
};
Functions
Address.parse(address: []const u8) Error!Address
Parse a string address into an Address struct.
Parameters:
address: String representation (e.g., "192.168.1.1:8080" or "[::1]:8080")
Returns: Error!Address - Parsed address or error
Example:
const core = @import("core");
const addr = try core.Address.parse("192.168.1.10:8080");
const ipv6_addr = try core.Address.parse("[2001:db8::1]:8080");
Address.toString(self: Address) Error![64]u8
Convert Address to string representation.
Parameters:
self: Address instance
Returns: Error![64]u8 - String representation
Example:
const core = @import("core");
const addr = try core.Address.parse("127.0.0.1:8080");
const str = try addr.toString();
// str = "127.0.0.1:8080"
Address.isValid(self: Address) bool
Validate address structure.
Parameters:
self: Address instance
Returns: bool - True if valid
buffer.zig - Buffer Management
Types
pub const BufferType = enum(u8) {
stream = 1, // Stream-oriented (TCP-like)
packet = 2, // Packet-oriented (UDP-like)
message = 3, // Message-oriented (application protocol)
};
pub const BufferFlags = packed struct(u8) {
read_only: bool = false,
owns_data: bool = true,
compressed: bool = false,
encrypted: bool = false,
priority: u3 = 0, // 0-7 priority levels
_padding: u1 = 0,
};
Buffer Pool Functions
BufferPool.init(config: PoolConfig, allocator: std.mem.Allocator) BufferPool
Create a new buffer pool with specified configuration.
Parameters:
config: Pool configurationallocator: Memory allocator
Returns: BufferPool - Created buffer pool
Example:
const core = @import("core");
const std = @import("std");
const allocator = std.heap.page_allocator;
const config = core.buffer.PoolConfig{
.min_chunk_size = 1024,
.max_chunk_size = 1024 * 1024,
.initial_chunks = 8,
.max_chunks = 256,
};
var pool = core.BufferPool.init(config, allocator);
defer pool.deinit();
BufferPool.acquire(self: *BufferPool, size: usize) Error![]u8
Acquire a buffer from the pool.
Parameters:
self: Buffer pool instancesize: Required buffer size
Returns: Error![]u8 - Allocated buffer or error
Example:
const buffer = try pool.acquire(4096);
defer pool.release(buffer);
socket.zig - Socket Operations
Types
pub const SocketProtocol = enum(u8) {
tcp = 1,
udp = 2,
unix_stream = 3,
unix_dgram = 4,
};
pub const SocketConfig = struct {
protocol: SocketProtocol,
non_blocking: bool = false,
reuse_address: bool = true,
reuse_port: bool = false,
keep_alive: bool = false,
no_delay: bool = true,
buffer_size: usize = 64 * 1024,
timeout_ms: u32 = 30000,
multicast_ttl: u8 = 1,
bind_interface: ?[]const u8 = null,
};
pub const SocketState = enum(u8) {
created = 0,
opened = 1,
bound = 2,
listening = 3,
connected = 4,
closed = 5,
};
Functions
Socket.create(config: SocketConfig, allocator: std.mem.Allocator) Error!Socket
Create a new socket with configuration.
Parameters:
config: Socket configurationallocator: Memory allocator
Returns: Error!Socket - Created socket or error
Example:
const core = @import("core");
const std = @import("std");
const allocator = std.heap.page_allocator;
const config = core.SocketConfig{
.protocol = .tcp,
.reuse_address = true,
.no_delay = true,
};
var tcp_socket = try core.Socket.create(config, allocator);
defer tcp_socket.deinit();
Socket.deinit(self: *Socket) void
Destroy socket and release resources.
Parameters:
self: Socket instance
Example:
socket.deinit();
Socket.bind(self: *Socket, address: Address) Error!void
Bind socket to address.
Parameters:
self: Socket instanceaddress: Address to bind to
Returns: Error!void - Error on bind failure
Example:
const core = @import("core");
const addr = try core.Address.parse("0.0.0.0:8080");
try socket.bind(addr);
Socket.listen(self: *Socket, backlog: u32) Error!void
Start listening for connections (TCP only).
Parameters:
self: Socket instancebacklog: Maximum pending connections
Returns: Error!void - Error on listen failure
Example:
try socket.listen(10);
Socket.connect(self: *Socket, address: Address) Error!void
Connect to remote address (TCP only).
Parameters:
self: Socket instanceaddress: Remote address
Returns: Error!void - Error on connect failure
Example:
const core = @import("core");
const remote_addr = try core.Address.parse("192.168.1.10:8080");
try socket.connect(remote_addr);
Socket.accept(self: *Socket) Error!Socket
Accept incoming connection (TCP only).
Parameters:
self: Listening socket
Returns: Error!Socket - Accepted connection socket
Example:
const client_socket = try server_socket.accept();
defer client_socket.deinit();
Socket.send(self: *Socket, data: []const u8) Error!usize
Send data through socket.
Parameters:
self: Socket instancedata: Data to send
Returns: Error!usize - Number of bytes sent
Example:
const message = "Hello!";
const sent = try socket.send(message);
Socket.receive(self: *Socket, buffer: []u8) Error!usize
Receive data from socket.
Parameters:
self: Socket instancebuffer: Buffer to receive into
Returns: Error!usize - Number of bytes received
Example:
var receive_buffer: [1024]u8 = undefined;
const received = try socket.receive(&receive_buffer);
Socket.close(self: *Socket) void
Close socket.
Parameters:
self: Socket instance
Example:
socket.close();
connection.zig - Connection Management
Types
pub const ConnectionType = enum(u8) {
tcp = 1,
udp = 2,
unix_stream = 3,
unix_dgram = 4,
};
pub const ConnectionState = enum(u8) {
disconnected = 0,
connecting = 1,
connected = 2,
closing = 3,
closed = 4,
failed = 5,
};
pub const ConnectionConfig = struct {
connection_type: ConnectionType,
buffer_size: usize = 64 * 1024,
timeout_ms: u32 = 30000,
keep_alive: bool = true,
no_delay: bool = true,
max_retry_attempts: u3 = 3,
retry_delay_ms: u32 = 1000,
health_check_interval: u32 = 30000,
enable_metrics: bool = true,
};
Functions
Connection.init(config: ConnectionConfig, allocator: std.mem.Allocator) Error!Connection
Initialize a new connection.
Parameters:
config: Connection configurationallocator: Memory allocator
Returns: Error!Connection - Created connection or error
Example:
const core = @import("core");
const std = @import("std");
const config = core.ConnectionConfig{
.connection_type = .tcp,
.buffer_size = 4096,
.timeout_ms = 10000,
.keep_alive = true,
.no_delay = true,
.enable_metrics = true,
};
var connection = try core.Connection.init(config, allocator);
defer connection.deinit();
Connection.deinit(self: *Connection) void
Destroy connection and release resources.
Parameters:
self: Connection instance
Example:
connection.deinit();
Connection.connect(self: *Connection, address: Address) Error!void
Connect to remote address.
Parameters:
self: Connection instanceaddress: Remote address
Returns: Error!void - Error on connection failure
Example:
const core = @import("core");
const remote_addr = try core.Address.parse("192.168.1.10:8080");
try connection.connect(remote_addr);
Connection.send(self: *Connection, data: []const u8) Error!usize
Send data through connection.
Parameters:
self: Connection instancedata: Data to send
Returns: Error!usize - Number of bytes sent
Example:
const message = "Hello, P2P!";
const sent = try connection.send(message);
Connection.receive(self: *Connection, buffer: []u8) Error!usize
Receive data from connection.
Parameters:
self: Connection instancebuffer: Buffer to receive into
Returns: Error!usize - Number of bytes received
Example:
var receive_buffer: [1024]u8 = undefined;
const received = try connection.receive(&receive_buffer);
Connection.close(self: *Connection) void
Close connection gracefully.
Parameters:
self: Connection instance
Example:
connection.close();
ConnectionStats.recordSend(self: *ConnectionStats, bytes: usize, message_count: u64) void
Record sent data statistics.
Parameters:
self: Connection stats instancebytes: Number of bytes sentmessage_count: Number of messages sent
Example:
connection.stats.recordSend(1024, 1);
ConnectionStats.recordReceive(self: *ConnectionStats, bytes: usize, message_count: u64) void
Record received data statistics.
Parameters:
self: Connection stats instancebytes: Number of bytes receivedmessage_count: Number of messages received
Example:
connection.stats.recordReceive(512, 1);
Network Module
The network module provides network-level abstractions for P2P communication including peer management, discovery protocols, network topology, and routing algorithms.
node.zig - Node Management
Types
pub const NodeState = enum(u8) {
Offline = 0,
Starting = 1,
Online = 2,
ShuttingDown = 3,
Maintenance = 4,
};
pub const RoutingDecision = struct {
should_forward: bool,
next_hop: ?PeerId,
reason: RoutingReason,
confidence: u8,
};
pub const RoutingReason = enum(u8) {
Direct = 1,
ForwardToNeighbor = 2,
UseRoutingTable = 3,
Broadcast = 4,
NoRoute = 5,
Expired = 6,
Congestion = 7,
};
peer.zig - Peer Management
Types
pub const PeerId = [32]u8;
pub const PeerState = enum(u8) {
disconnected = 0,
connecting = 1,
connected = 2,
failed = 3,
};
Functions
PeerId.generate() PeerId
Generate a new random peer ID.
Returns: PeerId - New peer identifier
Example:
const network = @import("network");
const peer_id = network.PeerId.generate();
Peer.init(allocator: std.mem.Allocator, address: Address) Error!Peer
Initialize a new peer.
Parameters:
allocator: Memory allocatoraddress: Peer network address
Returns: Error!Peer - Created peer or error
Example:
const network = @import("network");
const core = @import("core");
const std = @import("std");
const addr = try core.Address.parse("192.168.1.10:8080");
var peer = try network.Peer.init(allocator, addr);
defer peer.deinit();
discovery.zig - Peer Discovery
Types
pub const DiscoveryConfig = struct {
// Configuration options for discovery
};
pub const DiscoveryState = enum(u8) {
// Discovery states
};
Functions
DiscoveryManager.findPeers(self: *DiscoveryManager, count: usize) Error![]Peer
Find peers in the network.
Parameters:
self: Discovery manager instancecount: Maximum number of peers to find
Returns: Error![]Peer - Array of discovered peers
Example:
const network = @import("network");
const peers = try discovery.findPeers(10);
defer allocator.free(peers);
topology.zig - Network Topology Management
Types
pub const TopologyType = enum(u8) {
// Topology types
};
Functions
NetworkTopology.addNode(self: *NetworkTopology, peer: Peer) Error!void
Add peer to network topology.
Parameters:
self: Network topology instancepeer: Peer to add
Returns: Error!void - Error on failure
Example:
const network = @import("network");
try topology.addNode(peer);
Protocol Module
The protocol module provides the protocol layer for P2P communication including message definitions, serialization, routing logic, and handler registration.
message.zig - Message System
Types
pub const MessageId = u64;
pub const NodeId = [32]u8;
pub const MessageType = enum(u16) {
ping = 0x01,
pong = 0x02,
find_node = 0x03,
nodes = 0x04,
store = 0x05,
find_value = 0x06,
value = 0x07,
discovery_hello = 0x10,
discovery_response = 0x11,
discovery_announce = 0x12,
topology_query = 0x20,
custom = 0x1000,
};
pub const MessageHeader = struct {
magic: u32,
version: u16,
msg_type: MessageType,
flags: u8,
id: MessageId,
source: NodeId,
dest: NodeId,
priority: u8,
ttl: u8,
timestamp: i64,
reserved: u8,
};
pub const BaseMessage = struct {
header: MessageHeader,
payload: []const u8,
};
Functions
MessageHeader.init(msg_type: MessageType, id: MessageId, source: NodeId, dest: NodeId) MessageHeader
Create a new message header.
Parameters:
msg_type: Type of messageid: Message identifiersource: Source node IDdest: Destination node ID
Returns: MessageHeader - Created message header
Example:
const protocol = @import("protocol");
const std = @import("std");
const msg_id: u64 = 12345;
const source_id: [32]u8 = std.mem.zeroes([32]u8);
const dest_id: [32]u8 = std.mem.zeroes([32]u8);
const header = protocol.MessageHeader.init(.ping, msg_id, source_id, dest_id);
BaseMessage.getType(self: BaseMessage) MessageType
Get message type.
Parameters:
self: Message instance
Returns: MessageType - Message type
Example:
const msg_type = message.getType();
BaseMessage.decrementTTL(self: *BaseMessage) bool
Decrement message TTL (time to live).
Parameters:
self: Message instance
Returns: bool - True if TTL is still valid
Example:
if (message.decrementTTL()) {
// Message can still be forwarded
}
serializer.zig - Message Serialization
Functions
MessageSerializer.serialize(message: BaseMessage, allocator: std.mem.Allocator) Error![]u8
Serialize message to binary format.
Parameters:
message: Message to serializeallocator: Memory allocator
Returns: Error![]u8 - Serialized binary data
Example:
const protocol = @import("protocol");
const std = @import("std");
const serialized = try protocol.MessageSerializer.serialize(message, allocator);
defer allocator.free(serialized);
MessageSerializer.deserialize(data: []const u8, allocator: std.mem.Allocator) Error!BaseMessage
Deserialize message from binary format.
Parameters:
data: Serialized message dataallocator: Memory allocator
Returns: Error!BaseMessage - Deserialized message
Example:
const protocol = @import("protocol");
const std = @import("std");
const message = try protocol.MessageSerializer.deserialize(data, allocator);
defer allocator.free(message.payload);
handler.zig - Message Handling
Types
pub const HandlerFunc = *const fn (message: BaseMessage, connection: *Connection) Error!void;
Functions
HandlerRegistry.register(self: *HandlerRegistry, message_type: MessageType, handler: HandlerFunc) Error!void
Register a message handler.
Parameters:
self: Handler registry instancemessage_type: Message type to handlehandler: Handler function
Returns: Error!void - Error on registration failure
Example:
const protocol = @import("protocol");
fn handlePing(message: protocol.BaseMessage, connection: *core.Connection) !void {
// Handle ping message
}
try registry.register(.ping, handlePing);
HandlerRegistry.handle(self: *HandlerRegistry, message: BaseMessage, connection: *Connection) Error!void
Handle incoming message.
Parameters:
self: Handler registry instancemessage: Message to handleconnection: Connection the message arrived on
Returns: Error!void - Error on handling failure
Example:
try registry.handle(message, connection);
router.zig - Message Routing
Types
pub const RouteResult = enum(u8) {
delivered = 1,
forwarded = 2,
dropped = 3,
queued = 4,
};
Functions
MessageRouter.route(self: *MessageRouter, message: BaseMessage) Error!RouteResult
Route a message to its destination.
Parameters:
self: Message router instancemessage: Message to route
Returns: Error!RouteResult - Routing result
Example:
const protocol = @import("protocol");
const result = try router.route(message);
switch (result) {
.delivered => std.debug.print("Message delivered\n", .{}),
.forwarded => std.debug.print("Message forwarded\n", .{}),
.dropped => std.debug.print("Message dropped\n", .{}),
.queued => std.debug.print("Message queued\n", .{}),
}
Files Module
The files module provides file sharing functionality including hashing, piece management, upload/download, and transfer protocols.
hash.zig - Cryptographic Hashing
Functions
HashUtils.computeSHA256(data: []const u8) [32]u8
Compute SHA-256 hash of data.
Parameters:
data: Data to hash
Returns: [32]u8 - SHA-256 hash
Example:
const files = @import("files");
const std = @import("std");
const file_data = try std.fs.cwd().readFileAlloc(allocator, "file.txt");
defer allocator.free(file_data);
const hash = files.HashUtils.computeSHA256(file_data);
HashUtils.computePieceHash(data: []const u8) PieceHash
Compute hash for a file piece.
Parameters:
data: Piece data to hash
Returns: PieceHash - Piece hash
Example:
const files = @import("files");
const piece_hash = files.HashUtils.computePieceHash(piece_data);
file.zig - File Management
Types
pub const FileType = enum(u8) {
regular = 1,
directory = 2,
symlink = 3,
};
Functions
FileReader.open(file_path: []const u8, allocator: std.mem.Allocator) Error!FileReader
Open a file for reading.
Parameters:
file_path: Path to fileallocator: Memory allocator
Returns: Error!FileReader - File reader instance or error
Example:
const files = @import("files");
const std = @import("std");
var reader = try files.FileReader.open("document.pdf", allocator);
defer reader.close();
FileWriter.create(file_path: []const u8, allocator: std.mem.Allocator) Error!FileWriter
Create a file for writing.
Parameters:
file_path: Path to fileallocator: Memory allocator
Returns: Error!FileWriter - File writer instance or error
Example:
const files = @import("files");
const std = @import("std");
var writer = try files.FileWriter.create("output.pdf", allocator);
defer writer.close();
piece.zig - Piece Management
Functions
PieceManager.splitFile(self: *PieceManager, file_path: []const u8, piece_size: usize) Error![]PieceHash
Split file into pieces.
Parameters:
self: Piece manager instancefile_path: Path to filepiece_size: Size of each piece in bytes
Returns: Error![]PieceHash - Array of piece hashes
Example:
const files = @import("files");
const pieces = try piece_manager.splitFile("large_file.bin", 256 * 1024);
defer allocator.free(pieces);
download.zig - Download Management
Functions
DownloadManager.startDownload(self: *DownloadManager, file_hash: [32]u8, peers: []Peer) Error!void
Start downloading a file.
Parameters:
self: Download manager instancefile_hash: Hash of file to downloadpeers: List of peers to download from
Returns: Error!void - Error on failure
Example:
const files = @import("files");
const network = @import("network");
const file_hash: [32]u8 = // ... file hash
const peers = try discovery.findPeers(10);
defer allocator.free(peers);
try download_manager.startDownload(file_hash, peers);
DownloadManager.getProgress(self: *DownloadManager, file_hash: [32]u8) f32
Get download progress (0.0 to 1.0).
Parameters:
self: Download manager instancefile_hash: Hash of downloading file
Returns: f32 - Progress as fraction
Example:
const progress = download_manager.getProgress(file_hash);
std.debug.print("Download progress: {d:.1}%\n", .{progress * 100.0});
upload.zig - Upload Management
Functions
UploadManager.startUpload(self: *UploadManager, file_path: []const u8, peer: Peer) Error!void
Start uploading a file.
Parameters:
self: Upload manager instancefile_path: Path to file to uploadpeer: Peer to upload to
Returns: Error!void - Error on failure
Example:
const files = @import("files");
const network = @import("network");
try upload_manager.startUpload("document.pdf", peer);
transfer.zig - Transfer Protocol
Functions
TransferProtocol.negotiateTransfer(self: *TransferProtocol, peer: Peer, file_hash: [32]u8) Error!void
Negotiate a file transfer with peer.
Parameters:
self: Transfer protocol instancepeer: Peer to negotiate withfile_hash: Hash of file to transfer
Returns: Error!void - Error on failure
Example:
const files = @import("files");
const network = @import("network");
try transfer_protocol.negotiateTransfer(peer, file_hash);
manager.zig - File Sharing Manager
Types
pub const FileSharingConfig = struct {
// Configuration options
pub fn default() FileSharingConfig;
pub fn high_performance() FileSharingConfig;
pub fn low_bandwidth() FileSharingConfig;
};
Functions
FileSharingManager.init(config: FileSharingConfig, allocator: std.mem.Allocator) Error!FileSharingManager
Initialize file sharing manager.
Parameters:
config: File sharing configurationallocator: Memory allocator
Returns: Error!FileSharingManager - Manager instance or error
Example:
const files = @import("files");
const std = @import("std");
const config = files.FileSharingConfig.default();
var manager = try files.FileSharingManager.init(config, allocator);
defer manager.deinit();
createFileSharingSystem(config: FileSharingConfig, allocator: std.mem.Allocator) Error!FileSharingManager
Complete file sharing system initialization.
Parameters:
config: File sharing configurationallocator: Memory allocator
Returns: Error!FileSharingManager - Manager instance or error
Example:
const files = @import("files");
const std = @import("std");
const config = files.FileSharingConfig.high_performance();
var system = try files.createFileSharingSystem(config, allocator);
defer system.deinit();
Error Types
pub const Error = error{
// Network errors
NetworkError,
ConnectionRefused,
Timeout,
AddressInUse,
NetworkUnreachable,
AddressParseError,
// Protocol errors
ProtocolError,
InvalidMessage,
UnsupportedMessage,
MessageTooLarge,
ChecksumMismatch,
// Cryptographic errors
CryptoError,
InvalidSignature,
KeyNotFound,
EncryptionFailed,
DecryptionFailed,
// File errors
FileNotFound,
PermissionDenied,
DiskFull,
FileCorrupted,
// System errors
OutOfMemory,
ThreadError,
InvalidArgument,
InvalidState,
ResourceBusy,
// Buffer errors
BufferTooSmall,
BufferOverflow,
// Socket errors
SocketError,
BindFailed,
ListenFailed,
AcceptFailed,
ConnectFailed,
};
Data Structures
Error Types
All functions in the library return Error!T where T is the return type. Common error patterns:
- Network errors: Connection failures, timeouts, network unreachability, address parsing errors
- Protocol errors: Invalid messages, unsupported features, checksum mismatches
- Crypto errors: Signature failures, encryption/decryption issues
- File errors: File not found, permission denied, corruption
- System errors: Out of memory, invalid arguments, resource busy
- Buffer errors: Buffer too small, buffer overflow
- Socket errors: Socket creation, bind, listen, accept, and connect failures
Memory Management
The library uses Zig's allocators for memory management:
- Use
std.heap.GeneralPurposeAllocatorfor general purposes - Use
std.heap.page_allocatorfor simple programs - Always call
deinit()on allocated resources - Free allocated memory using the same allocator
Thread Safety
All public APIs are thread-safe:
- Connection operations are protected by internal locks
- Message handlers can be called from multiple threads
- File operations are synchronized
- Use proper allocator synchronization for custom allocators
- Statistics use atomic operations for thread-safe updates
Complete Usage Example
Here's a complete example showing how to use the library:
const std = @import("std");
const core = @import("core");
const network = @import("network");
const protocol = @import("protocol");
const files = @import("files");
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
// Create connection
const config = core.ConnectionConfig{
.connection_type = .tcp,
.buffer_size = 4096,
.timeout_ms = 10000,
.keep_alive = true,
.no_delay = true,
.enable_metrics = true,
};
var connection = try core.Connection.init(config, allocator);
defer connection.deinit();
// Connect to remote peer
const remote_addr = try core.Address.parse("192.168.1.10:8080");
try connection.connect(remote_addr);
// Create and send message
const msg_id: u64 = 12345;
const source_id: [32]u8 = std.mem.zeroes([32]u8);
const dest_id: [32]u8 = std.mem.zeroes([32]u8);
const header = protocol.MessageHeader.init(.ping, msg_id, source_id, dest_id);
const message = protocol.BaseMessage{
.header = header,
.payload = "Hello, P2P!",
};
const serialized = try protocol.MessageSerializer.serialize(message, allocator);
defer allocator.free(serialized);
const sent = try connection.send(serialized);
std.debug.print("Sent {} bytes\n", .{sent});
}
This API reference covers the complete public interface of the P2P library. For usage examples and tutorials, see the User Guide.