TcpStream

struct TcpStream

A thin synchronous wrapper around a connected TCP file descriptor.

Construction and I/O expose raw host success or negative errno integers; unlike fs.File, this type does not wrap failures in Result. Callers must check is_valid after connect and inspect read/write return values.

Properties

let fd: Int

The host file descriptor.

Methods

func connect(addr: Int, port: Int) -> TcpStream

Creates an IPv4 stream socket and attempts to connect it to addr:port.

The current API discards the connect result and always wraps the socket descriptor. is_valid detects socket-creation failure only; it does not prove that the connection succeeded.

View Source
pub func connect(addr: Int, port: Int) -> TcpStream {
	let fd = _io_socket(domain: AF_INET, socktype: SOCK_STREAM, proto: 0)
	_io_connect(fd: fd, addr: addr, port: port)
	TcpStream(fd: fd)
}

func read(buf: RawPtr, count: Int) -> Int

Performs one socket read into caller-owned raw storage.

The caller must provide at least count writable bytes. The result can be a short byte count, zero at EOF, or a negative errno; no retry is attempted.

View Source
pub func read(buf: RawPtr, count: Int) -> Int {
	_io_read(fd: self.fd, buf: buf, count: count)
}

func read_string(max: Int) -> String

Performs one read into a newly allocated buffer of max bytes.

max must be non-negative. Short reads are returned immediately. Negative or dishonest host counts are clamped to zero or max; this is byte transport and does not validate UTF-8.

View Source
pub func read_string(max: Int) -> String {
	#unsafe {
		let buf = _alloc<Byte>(count: max)
		let n = _io_clamp(
			count: _io_read(fd: self.fd, buf: buf, count: max),
			capacity: max
		)
		String(base: ByteStorage(base: buf), byte_count: n, capacity: max)
	}
}

func write(buf: RawPtr, count: Int) -> Int

Performs one socket write from caller-owned raw storage.

The result can be a short count or negative errno; callers requiring a full write must loop over the unwritten suffix.

View Source
pub func write(buf: RawPtr, count: Int) -> Int {
	_io_write(fd: self.fd, buf: buf, count: count)
}

func write_string(s: String) -> Int

Requests one socket write for the complete string buffer.

The host may report a short write; this convenience method does not retry.

View Source
pub func write_string(s: String) -> Int {
	_io_write(fd: self.fd, buf: s.storage.base, count: s.byte_count)
}

func close() -> Int

Requests one host close and returns zero or a negative errno.

The stored descriptor is not invalidated, so callers must avoid repeated closes and later I/O through this value.

View Source
pub func close() -> Int {
	_io_close(fd: self.fd)
}

func is_valid() -> Bool

Returns whether socket creation produced a non-negative descriptor.

A true result does not prove that connect succeeded because that reply is not retained by the current constructor.

View Source
pub func is_valid() -> Bool { self.fd >= 0 }