dmsc/c/fs.rs
1//! Copyright © 2025-2026 Wenze Wei. All Rights Reserved.
2//!
3//! This file is part of DMSC.
4//! The DMSC project belongs to the Dunimd Team.
5//!
6//! Licensed under the Apache License, Version 2.0 (the "License");
7//! You may not use this file except in compliance with the License.
8//! You may obtain a copy of the License at
9//!
10//! http://www.apache.org/licenses/LICENSE-2.0
11//!
12//! Unless required by applicable law or agreed to in writing, software
13//! distributed under the License is distributed on an "AS IS" BASIS,
14//! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15//! See the License for the specific language governing permissions and
16//! limitations under the License.
17
18//! # File System Module C API
19//!
20//! This module provides C language bindings for DMSC's file system abstraction layer. The file
21//! system module delivers cross-platform file and directory operations with unified interfaces
22//! across different operating systems. This C API enables C/C++ applications to leverage DMSC's
23//! file handling capabilities including path manipulation, file I/O operations, directory
24//! traversal, symbolic link management, and file metadata operations.
25//!
26//! ## Module Architecture
27//!
28//! The file system module provides a single primary component:
29//!
30//! - **DMSCFileSystem**: Unified file system abstraction providing portable file and directory
31//! operations. The abstraction layer normalizes platform differences while preserving access
32//! to platform-specific features when needed. The file system object provides methods for
33//! reading, writing, creating, deleting, and managing files and directories across Windows,
34//! Linux, and macOS platforms.
35//!
36//! ## Cross-Platform Design
37//!
38//! The file system module implements comprehensive cross-platform compatibility:
39//!
40//! - **Path Representation**: Uses abstract path representation that normalizes platform-specific
41//! path separators, conventions, and edge cases. Supports both Windows-style paths (C:\)
42//! and Unix-style paths (/). Path operations handle relative and absolute paths uniformly.
43//!
44//! - **File Operations**: Provides consistent file I/O semantics across platforms including
45//! atomic file operations, proper handling of file locks, and consistent error semantics.
46//! Supports both blocking and asynchronous file operations through the Tokio integration.
47//!
48//! - **Directory Operations**: Cross-platform directory traversal, creation, and management.
49//! Handles differences in directory structures, permissions, and special directories
50//! across operating systems.
51//!
52//! - **Symbolic Links**: Proper handling of symbolic links on platforms that support them.
53//! Detects link loops, resolves link targets, and provides control over link resolution.
54//!
55//! - **Metadata Access**: Uniform interface to file metadata including size, timestamps,
56//! permissions, and file type information. Handles platform-specific metadata differences.
57//!
58//! ## Supported Operations
59//!
60//! The file system module provides comprehensive file and directory operations:
61//!
62//! - **Path Operations**: Join paths, normalize paths, resolve relative paths to absolute,
63//! extract components (filename, extension, parent directory), and check path properties.
64//!
65//! - **File I/O**: Open files for reading, writing, or appending with various sharing modes.
66//! Read and write operations with configurable buffering. Support for memory-mapped files
67//! for large file operations.
68//!
69//! - **Directory Operations**: Create directories (including nested paths), list directory
70//! contents, iterate directories recursively, remove directories (with or without contents).
71//!
72//! - **File Management**: Copy files (with optional overwrite), move/rename files, delete
73//! files, check file existence, and create temporary files.
74//!
75//! - **Metadata Operations**: Get file size, access/modification/creation times, file
76//! permissions, and file type (regular file, directory, symlink, etc.).
77//!
78//! - **Permission Management**: Get and set file permissions (Unix mode bits, Windows ACLs).
79//! Handle permission propagation and default permissions for new files.
80//!
81//! ## File Operations Modes
82//!
83//! Files can be opened with various modes controlling access and behavior:
84//!
85//! - **Read Mode**: Open file for reading only. Multiple readers allowed concurrently.
86//!
87//! - **Write Mode**: Open file for writing. Truncates existing file by default.
88//! Exclusive access for writing.
89//!
90//! - **Append Mode**: Open file for writing at end only. Multiple appenders allowed.
91//! Preserves existing content.
92//!
93//! - **Create Mode**: Create file if it doesn't exist. Fail if file exists.
94//!
95//! - **Truncate Mode**: Truncate file to zero length when opened.
96//!
97//! - **Binary Mode**: Open file for binary data (no text translation).
98//!
99//! - **Text Mode**: Open file for text data with platform-specific line ending handling.
100//!
101//! ## Performance Characteristics
102//!
103//! File operations have the following performance profiles:
104//!
105//! - File open: O(1) typically, O(log n) for deep directory traversal
106//! - Sequential read: O(n) where n is bytes read, optimized by OS caching
107//! - Random read: O(1) per read operation, may cause disk seeks
108//! - Directory listing: O(n) where n is directory entry count
109//! - Metadata queries: O(1) for cached metadata, O(log n) otherwise
110//!
111//! ## Asynchronous Operations
112//!
113//! The file system module supports asynchronous operations through Tokio integration:
114//!
115//! - Async file I/O for high-concurrency scenarios
116//! - Non-blocking directory iteration
117//! - Cancellation support for long-running operations
118//! - Proper integration with async/await patterns
119//!
120//! ## Memory Management
121//!
122//! All C API objects use opaque pointers with manual memory management:
123//!
124//! - Constructor functions allocate new instances on the heap
125//! - Destructor functions must be called to release memory
126//! - File handles must be properly closed after use
127//! - Path strings must be freed after use
128//!
129//! ## Thread Safety
130//!
131//! The underlying implementations provide:
132//!
133//! - File handles are not thread-safe (use synchronization for concurrent access)
134//! - File system instance is thread-safe for metadata queries
135//! - Path resolution operations are thread-safe
136//! - Consider using separate handles for concurrent file operations
137//!
138//! ## Error Handling
139//!
140//! File operations return error codes with optional messages:
141//!
142//! - Error codes follow standard POSIX conventions where possible
143//! - Platform-specific errors are mapped to portable error codes
144//! - Detailed error messages available for debugging
145//! - Permission errors distinguished from other access errors
146//!
147//! ## Usage Example
148//!
149//! ```c
150//! // Create file system instance with automatic root detection
151//! DMSCFileSystem* fs = dmsc_fs_new_auto();
152//! if (fs == NULL) {
153//! fprintf(stderr, "Failed to create file system\n");
154//! return ERROR_FILESYSTEM;
155//! }
156//!
157//! // Read file contents
158//! char* content = NULL;
159//! size_t size = 0;
160//! int result = dmsc_fs_read_file(fs, "/path/to/file.txt", &content, &size);
161//!
162//! if (result == 0 && content != NULL) {
163//! printf("Read %zu bytes: %.*s\n", size, (int)size, content);
164//! dmsc_fs_string_free(content);
165//! }
166//!
167//! // Write to file
168//! const char* data = "Hello, World!";
169//! result = dmsc_fs_write_file(fs, "/path/to/output.txt", data, strlen(data));
170//!
171//! if (result != 0) {
172//! fprintf(stderr, "Failed to write file: %s\n", dmsc_fs_last_error(fs));
173//! }
174//!
175//! // List directory contents
176//! char** entries = NULL;
177//! size_t entry_count = 0;
178//! result = dmsc_fs_list_dir(fs, "/path/to/directory", &entries, &entry_count);
179//!
180//! if (result == 0) {
181//! for (size_t i = 0; i < entry_count; i++) {
182//! printf(" %s\n", entries[i]);
183//! dmsc_fs_string_free(entries[i]);
184//! }
185//! free(entries);
186//! }
187//!
188//! // Cleanup
189//! dmsc_fs_free(fs);
190//! ```
191//!
192//! ## Dependencies
193//!
194//! This module depends on the following DMSC components:
195//!
196//! - `crate::fs`: Rust file system module implementation
197//! - `crate::prelude`: Common types and traits
198//!
199//! ## Feature Flags
200//!
201//! The file system module is always enabled as it provides fundamental infrastructure
202//! for file operations in DMSC applications.
203
204use crate::fs::DMSCFileSystem;
205
206
207c_wrapper!(CDMSCFileSystem, DMSCFileSystem);
208
209/// Creates a new DMSCFileSystem instance with automatic root directory detection.
210///
211/// Initializes a file system abstraction with automatic detection of the root directory
212/// and appropriate platform configuration. The created instance can perform all
213/// supported file operations on the local file system.
214///
215/// # Returns
216///
217/// Pointer to newly allocated DMSCFileSystem on success, or NULL if:
218/// - Memory allocation fails
219/// - Root directory detection fails
220/// - Platform initialization fails
221///
222/// # Automatic Detection
223///
224/// The function detects and configures:
225///
226/// - **Root Directory**: System root (/ on Unix, C:\ on Windows)
227/// - **Current Directory**: Process current working directory
228/// - **Temporary Directory**: Platform temp directory location
229/// - **Home Directory**: User home directory
230/// - **Path Separators**: Configured based on platform
231/// - **Case Sensitivity**: Determined by underlying file system
232///
233/// # Initial Capabilities
234///
235/// A newly created file system instance can:
236///
237/// - Perform all path operations
238/// - Access files in any accessible location
239/// - Create and manipulate files and directories
240/// - Query file metadata
241///
242/// # Usage Pattern
243///
244/// ```c
245/// DMSCFileSystem* fs = dmsc_fs_new_auto();
246/// if (fs == NULL) {
247/// fprintf(stderr, "File system initialization failed\n");
248/// return ERROR_INIT;
249/// }
250///
251/// // Use file system operations...
252///
253/// dmsc_fs_free(fs);
254/// ```
255///
256/// # Platform-Specific Notes
257///
258/// - **Windows**: Uses backslash path separator, supports UNC paths
259/// - **Linux/macOS**: Uses forward slash path separator, case-sensitive
260/// - **All Platforms**: Supports both relative and absolute paths
261#[no_mangle]
262pub extern "C" fn dmsc_fs_new_auto() -> *mut CDMSCFileSystem {
263 match DMSCFileSystem::new_auto_root() {
264 Ok(fs) => Box::into_raw(Box::new(CDMSCFileSystem::new(fs))),
265 Err(_) => std::ptr::null_mut(),
266 }
267}
268
269c_destructor!(dmsc_fs_free, CDMSCFileSystem);