| 1 | # clone-file |
| 2 | |
| 3 | A simple way to use your filesystem's [reflink] features. |
| 4 | |
| 5 | [reflink]: https://en.wikipedia.org/wiki/Data_deduplication#reflink |
| 6 | |
| 7 | ```rust |
| 8 | // Clone a file using a reflink, or error if it can not be done. |
| 9 | clone_file("src.bin", "dest.bin"); |
| 10 | |
| 11 | // Try to clone a file, falling back to a regular copy. |
| 12 | clone_or_copy_file("src.bin", "dest.bin"); |
| 13 | |
| 14 | // Clone a sub-range of a file using a reflink, or error if it can not be done. |
| 15 | clone_file_range( |
| 16 | "src.bin", |
| 17 | /* offset: */ 4 << 10, |
| 18 | /* length: */ 2 << 20, |
| 19 | "dest.bin", |
| 20 | /* dest offset: */ 0 |
| 21 | ); |
| 22 | |
| 23 | // Try to clone a sub-range of a file, falling back to a naive copy. |
| 24 | clone_or_copy_file_range( |
| 25 | "src.bin", |
| 26 | /* offset: */ 4 << 10, |
| 27 | /* length: */ 2 << 20, |
| 28 | "dest.bin", |
| 29 | /* dest offset: */ 0 |
| 30 | ); |
| 31 | ``` |
| 32 | |
| 33 | ## Implementation details |
| 34 | |
| 35 | ### Linux |
| 36 | |
| 37 | On Linux, `FICLONE` and `FICLONERANGE` ioctls are used. Please refer to [`man 2 ioctl_ficlonerange`] for details and limitations. |
| 38 | |
| 39 | Tested with the `btrfs` filesystem. |
| 40 | |
| 41 | [`man 2 ioctl_ficlonerange`]: https://man7.org/linux/man-pages/man2/ioctl_ficlonerange.2.html |
| 42 | |
| 43 | ### Others |
| 44 | |
| 45 | The `clone_file` and `clone_file_range` functions are currently not implemented for other platforms. |
| 46 | |
| 47 | However, the fallback functions `clone_or_copy_file` and `clone_or_copy_file_range` will work, falling back to naive copies. |
| 48 | |
| 49 | ## Running tests |
| 50 | |
| 51 | To test the cloning, we need a filesystem that supports reflinks. This requires a bit of a setup, which is implemented in the `test.sh` script. |
| 52 | |
| 53 | It expects a Linux system, with a `btrfs-progs` packages installed. It creates a 200MiB loopback device, formats it into `btrfs`, then creates the neccessary test data and runs `cargo tests`. It then cleans up the loopback and the mount. |
| 54 | |
| 55 | The tests are intentionally set up to run only through `test.sh` |