C API reference

libfsspec is the shared library that contains the process-wide filesystem registry and the built-in backends. Its interface is fsspec.h. The fsspec_sys crate declares the same interface for Rust.

Files

Item

Wheel location

Header

fsspec_rs/include/fsspec/fsspec.h

Library

fsspec_rs/lib/libfsspec.so, libfsspec.dylib, fsspec.dll

Link name

fsspec

Symbols

every exported function and type starts with fsspec_

Source

rust/capi (fsspec_capi crate), header generated by cbindgen

fsspec_rs reports these paths at runtime:

Function

Returns

fsspec_rs.get_prefix()

the package directory

fsspec_rs.get_include()

the directory containing fsspec/fsspec.h

fsspec_rs.get_library_dirs()

a list with the directory containing the library

fsspec_rs.get_libraries()

["fsspec"]

The extension module adds two functions:

Function

Returns

fsspec_rs.fsspec_rs.linked_to_libfsspec()

True when the extension uses libfsspec; False in Pyodide builds

fsspec_rs.fsspec_rs.protocols()

the protocols registered in the registry the extension uses, sorted

ABI version

FSSPEC_ABI_VERSION is the version the header describes; fsspec_abi_version() returns the version the loaded library was built with. Both are 1. Every vtable and factory struct starts with struct_size and abi_version. Registration fails with FSSPEC_INVALID_ARGUMENT when abi_version differs from the library’s, or when struct_size is smaller than those two fields or larger than 64 KiB. A struct shorter than the library’s is accepted; the missing trailing fields are treated as null.

Status codes

Most fallible functions return fsspec_status, a 32-bit enum:

Code

Value

Rust FsError

FSSPEC_OK

0

FSSPEC_NOT_FOUND

1

NotFound

FSSPEC_PERMISSION_DENIED

2

PermissionDenied

FSSPEC_ALREADY_EXISTS

3

AlreadyExists

FSSPEC_NOT_A_DIRECTORY

4

NotADirectory

FSSPEC_IS_A_DIRECTORY

5

IsADirectory

FSSPEC_IO

6

IoError

FSSPEC_INVALID_ARGUMENT

7

InvalidArgument

FSSPEC_NOT_SUPPORTED

8

NotSupported

FSSPEC_OTHER

9

Other

Function

Description

fsspec_last_error_message()

Message for the last failure on the calling thread, or null. Valid until the next failure on that thread.

fsspec_set_last_error(message, len)

Sets the thread’s message. Foreign backends call it before returning a failing status.

fsspec_clear_last_error()

Clears the thread’s message.

Panics inside libfsspec are caught at the boundary and returned as FSSPEC_OTHER.

Strings and memory

Arguments are UTF-8 pointer and length pairs and need no NUL terminator. Values that libfsspec returns are owned by the caller and freed with the matching function:

Type

Fields

Free with

fsspec_string

data (NUL-terminated), len (without the NUL)

fsspec_string_free

fsspec_string_list

items, len

fsspec_string_list_free

fsspec_bytes

data, len

fsspec_bytes_free

fsspec_file_info

name, size, file_type, created_ns, modified_ns, extra

fsspec_file_info_free

fsspec_file_info_list

items, len

fsspec_file_info_list_free

created_ns and modified_ns are nanoseconds since the Unix epoch, or -1 when unknown. file_type is FSSPEC_FILE_TYPE_FILE, FSSPEC_FILE_TYPE_DIRECTORY, or FSSPEC_FILE_TYPE_OTHER. extra contains backend-specific fields as alternating key and value strings.

All of these buffers use the platform allocator: malloc on Unix and HeapAlloc(GetProcessHeap(), ...) on Windows. Foreign backends allocate the values they return through vtable callbacks the same way, and libfsspec frees them.

Options

fsspec_options is a string-to-string map.

Function

Description

fsspec_options_new()

Creates an empty map.

fsspec_options_set(options, key, key_len, value, value_len)

Sets a key, replacing an earlier value.

fsspec_options_items(options, out)

Alternating key and value strings, sorted by key.

fsspec_options_free(options)

Frees the map. Null is ignored.

A null fsspec_options * argument means no options.

Registry

Function

Description

fsspec_url_to_fs(url, url_len, options, out_fs, out_path)

Resolves a URL through the registry. out_path, when not null, receives the path to use with the filesystem.

fsspec_register_filesystem(protocol, protocol_len, factory)

Registers a factory, replacing an earlier one and dropping its cached instances. The factory struct is copied.

fsspec_protocols(out)

Registered protocols, sorted.

fsspec_register_fallback(factory)

Installs the factory used for protocols nothing registered; null clears it. It is given the whole URL.

URL resolution, caching, and the built-in protocols (file, local, memory, s3) and their options are the same as the Rust registry; see “Filesystem registry” in the Rust reference.

fsspec_fs_factory:

Field

Description

struct_size

sizeof(fsspec_fs_factory)

abi_version

FSSPEC_ABI_VERSION

data

Passed to every callback.

create

Required. Builds a filesystem for a path and options; returns it in out.

instance_scope

Optional. Returns the part of the path that needs its own instance, such as a bucket.

release

Optional. Called with data when the registry drops the factory, such as when it is replaced.

Filesystems

fsspec_fs * is a reference-counted handle.

Function

Description

fsspec_fs_retain(fs)

Another handle to the same filesystem.

fsspec_fs_release(fs)

Frees a handle; the filesystem is dropped with its last handle.

fsspec_fs_protocols(fs, out)

Protocol names of the filesystem.

fsspec_fs_root_marker(fs, out), fsspec_fs_sep(fs, out)

Root marker and path separator.

fsspec_fs_strip_protocol(fs, path, path_len, out)

The path without its protocol prefix, as the backend normalises it; an empty result is the root marker.

fsspec_fs_unstrip_protocol(fs, path, path_len, out)

The path with the backend’s protocol prefix.

fsspec_fs_ls(fs, path, path_len, detail, out)

Lists a directory. With detail false, entries may contain only names.

fsspec_fs_info(fs, path, path_len, out)

Metadata for one path.

fsspec_fs_exists(fs, path, path_len, out)

Whether a path exists.

fsspec_fs_cat_file(fs, path, path_len, start, end, out)

Reads a file, or [*start, *end) when the pointers are not null. Negative offsets count from the end.

fsspec_fs_pipe_file(fs, path, path_len, data, data_len)

Writes a file, replacing it.

fsspec_fs_rm_file(fs, path, path_len)

Deletes one file.

fsspec_fs_cp_file(fs, src, src_len, dst, dst_len)

Copies one file within the filesystem.

fsspec_fs_mkdir(fs, path, path_len, create_parents)

Creates a directory.

fsspec_fs_rmdir(fs, path, path_len)

Removes an empty directory.

fsspec_fs_open(fs, path, path_len, mode, mode_len, out)

Opens a file with mode rb, wb, ab, or xb.

fsspec_fs_open_ex(fs, path, path_len, mode, mode_len, options, out)

As fsspec_fs_open, with open options block_size, max_blocks, autocommit, and cache_type (none, readahead, block, all). Vtable backends receive no options.

Object I/O and conditions

fsspec_fs_read(fs, path, path_len, options, out) returns bytes and their validator in fsspec_read_result. fsspec_fs_write(fs, path, path_len, bytes, bytes_len, options, out) returns the committed object’s validator in fsspec_write_result. Free successful outputs with fsspec_read_result_free and fsspec_write_result_free. On error, output storage is unchanged and must not be freed as a result.

These two functions return fsspec_operation_status, an int32_t. Values 0–9 retain the meanings above. status & FSSPEC_ERROR_KIND_MASK extracts the category: FSSPEC_CONFLICT (10), FSSPEC_GAP (11), FSSPEC_UNAVAILABLE (12), FSSPEC_TIMEOUT (13), FSSPEC_CORRUPT (14), FSSPEC_CANCELLED (15), and FSSPEC_UNKNOWN_OUTCOME (16) extend the legacy categories. A nonzero typed status may include FSSPEC_RETRY_SAFE; this bit means repeating the operation is safe. Unknown outcomes are never retry-safe. Zero still means success. Rust foreign adapters preserve category and retry metadata in both directions; old callbacks and legacy fsspec_status functions retain their existing contract. Existing functions and callbacks continue to return the original fsspec_status enum. Do not return conflict through a legacy callback.

Read and write option structs begin with struct_size; initialize it to the struct’s sizeof. Null options mean defaults. Read options include optional start and end pointers. Both include a condition pointer, with null meaning unconditional I/O. A condition has a kind and a borrowed validator pointer:

Kind

Validator

Meaning

FSSPEC_CONDITION_MATCH

Required, both scope and value strings

Operate only on the matching object.

FSSPEC_CONDITION_MISSING

Must be null

Create only if absent; invalid for reads.

Input pointers remain borrowed for the duration of the call. Result validators own both strings; both null means unavailable. Copy or retain the full validator when using it in a later request. Unknown condition kinds, short option structs, null output pointers and null byte pointers with nonzero lengths are invalid arguments. Validation occurs before writes.

fsspec_fs_io_capabilities(fs, out) reports read_match, write_match and write_missing. The filesystem vtable appends read, write and io_capabilities callbacks. Old shorter vtables remain valid: missing read/write callbacks use legacy I/O only for unconditional requests and reject conditions; a missing capability callback reports all flags false. Clients using the new symbols require a library that exports them, even though the ABI version remains 1.

Backend support and consistency guarantees match the Rust object I/O contract.

Native S3 object reads

fsspec_s3_open(bucket, bucket_len, options, out_fs, out_objects) constructs the built-in S3 backend and returns two owned handles sharing one client and runtime: a normal fsspec_fs and an opaque fsspec_object_store. Options use the registered S3 backend’s names and validation. This constructor bypasses registry lookup, protocol overrides and instance caching. Both output pointers must be nonnull and distinct. Failure leaves both outputs unchanged.

The object handle can be retained with fsspec_object_store_retain and released with fsspec_object_store_release; retain on null returns null and release on null is ignored. Each retained handle has its own release obligation. Filesystem and object handles may be released independently. Calls can run concurrently while their handles remain alive. These handles currently originate only from the built-in S3 constructor; no foreign object-store vtable is exposed.

Function

Result

Free with

fsspec_object_store_head(store, key, key_len, out)

fsspec_file_info, always a file, native modification time, optional etag and version extras

fsspec_file_info_free

fsspec_object_store_read_ranges(store, key, key_len, ranges, ranges_len, out)

fsspec_range_read_result, ordered byte buffers and validator

fsspec_range_read_result_free

Both reads return fsspec_operation_status and preserve structured error and retry metadata. Failure leaves the output unchanged. Keys are canonical nonempty bucket-relative paths, without URL or bucket stripping, percent decoding or the filesystem’s extra key escaping. Leading/trailing slashes, empty or dot segments, backslashes and control characters are invalid. HEAD never lists directories. head names its result with the supplied key. Modification times outside the nonnegative signed 64-bit nanosecond representation use the existing modified_ns = -1 sentinel.

Range reads reuse fsspec_byte_range, but require both bounds and 0 <= start < end within signed 64-bit limits. Starts at or past EOF fail; ends past EOF are clipped. Empty arrays perform no I/O. Requests use the built-in S3 coalescing and concurrency limits and verify an ETag across HEAD and all GETs. A missing ETag is unsupported. The complete output is retained in memory.

These are additive symbols: existing vtables and ABI version 1 are unchanged. Clients using these functions require a library exporting them; checking ABI version 1 alone does not establish their availability.

Range reads

fsspec_fs_read_ranges(fs, path, path_len, ranges, ranges_len, options, out) returns fsspec_operation_status. Its input is a borrowed array of fsspec_byte_range: start and end point to signed offsets, or are null for unbounded endpoints. The array may be null only when its length is zero. Input pointers remain valid for the duration of the call.

fsspec_range_read_options starts with struct_size, initialized to its sizeof, followed by condition, max_gap, max_request_size and max_concurrency. Null options use defaults of 65,536 bytes, 8,388,608 bytes and eight requests. Request size and concurrency must be positive. Conditions use the same representation as single-object reads.

Successful output is fsspec_range_read_result: an owned data array of fsspec_bytes, its len, and a shared validator. Call fsspec_range_read_result_free once to free the array, its buffers and validator. On failure output storage is unchanged. Null output pointers, invalid input arrays and short option structs are rejected before backend calls.

The filesystem vtable appends an optional read_ranges callback. Older shorter vtables retain coalesced sequential reads through their legacy callbacks and reject conditions. Native S3 retains concurrent pinned reads through both ABI directions. Existing status values, structs and callbacks retain their layouts. Clients using the new symbols require an updated library.

Range ordering, consistency and request limits follow the Rust range-read contract.

Files

fsspec_file * is an open file, closed with fsspec_file_close.

Function

Description

fsspec_file_read(file, buf, len, out_read)

Reads up to len bytes; *out_read is zero at end of file.

fsspec_file_write(file, data, len, out_written)

Writes bytes; out_written may be null.

fsspec_file_seek(file, offset, whence, out_position)

whence is 0 (start), 1 (current), or 2 (end).

fsspec_file_tell(file, out_position)

Current offset.

fsspec_file_flush(file)

Flushes buffered writes.

fsspec_file_size(file, out_size)

Size, or -1 when unknown.

fsspec_file_get_info(file, out)

Metadata for the open file.

fsspec_file_commit(file), fsspec_file_discard(file)

Commits or discards a transactional write.

fsspec_file_close(file)

Flushes, commits, and frees the handle. After commit or discard, it only frees. Failures discard pending writes before freeing. Null is ignored.

Async operations and dispatch

The async I/O contract documents operation/producer handles, managed and foreign event-loop dispatch, owned results/errors, cancellation, and deadlines. fsspec.h also exports read-only async filesystem/file vtables, shared budget contexts, and close operations that wait for cleanup. Native S3 streaming remains proposed; its draft constructor is not exported.

Foreign backends

fsspec_fs_from_vtable(vtable, data) wraps an implementation written outside libfsspec as an fsspec_fs *, and fsspec_file_from_vtable(vtable, data) does the same for an open file. Both copy the vtable, pass data to every callback, and return null with the error message set on failure.

fsspec_fs_vtable:

Field

Description

struct_size, abi_version

As for factories.

protocol

NUL-terminated, comma-separated protocol names, such as "file,local".

root_marker, sep

NUL-terminated strings; null uses the defaults.

ls, info, rm_file, cp_file, mkdir, rmdir, open

The FileSystem primitives. A null callback makes its operation return FSSPEC_NOT_SUPPORTED. Other operations, such as cat_file and exists, are derived from these.

release

Called with data when the last handle is released.

strip_protocol, unstrip_protocol, cat_file, pipe_file

Optional, after release. A backend that overrides these in Rust keeps its own behaviour across the ABI; null uses the derived defaults.

fsspec_file_vtable has read, write, seek, flush, size, info, commit, discard, and release. A null read, write, seek, or info returns FSSPEC_NOT_SUPPORTED; a null size reports -1; a null flush, commit, or discard succeeds without doing anything. release is called on close.

Rust bindings

The fsspec_sys crate declares the C functions without a #[link] attribute; the build links libfsspec (hatch-rs links) or compiles fsspec_capi in. It contains no registry state.

Item

Description

url_to_fs(url, &FsOptions)

Resolves a URL through libfsspec; returns a SharedFileSystem and the path.

register_filesystem(protocol, factory)

Registers a FilesystemFactory in libfsspec.

register_fallback(factory)

Installs or clears the factory for protocols nothing registered.

use_shared_registry()

Routes fsspec_rs::url_to_fs and register_filesystem through libfsspec.

protocols()

Registered protocols, sorted.

abi_version()

ABI version of the loaded library.

ForeignFileSystem, ForeignFile

FileSystem and FsFile implementations over libfsspec handles.

export_filesystem(fs), export_file(file)

Wrap Rust implementations as fsspec_fs * and fsspec_file *.

status_code, error_from_status, check, take_last_error

Conversions between FsError and status codes.

ffi, types

Raw declarations and repr(C) types of fsspec.h.