You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@commons.apache.org by pk...@apache.org on 2025/09/05 22:48:12 UTC

(commons-io) branch feat/file-systems created (now 37a647a69)

This is an automated email from the ASF dual-hosted git repository.

pkarwasz pushed a change to branch feat/file-systems
in repository https://gitbox.apache.org/repos/asf/commons-io.git


      at 37a647a69 feat: add length unit support in FileSystem limits

This branch includes the following new commits:

     new 37a647a69 feat: add length unit support in FileSystem limits

The 1 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.



(commons-io) 01/01: feat: add length unit support in FileSystem limits

Posted by pk...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

pkarwasz pushed a commit to branch feat/file-systems
in repository https://gitbox.apache.org/repos/asf/commons-io.git

commit 37a647a69b2c5ddb3446846b6ef807b7e3ebfd86
Author: Piotr P. Karwasz <pk...@apache.org>
AuthorDate: Sat Sep 6 00:44:04 2025 +0200

    feat: add length unit support in FileSystem limits
    
    Different filesystems and operating systems measure file and path lengths in different units:
    
    * macOS and Windows filesystems typically count **UTF-16 code units**.
    * Linux and other UNIX filesystems typically count **bytes**.
    
    This change introduces explicit unit support so these limits can be interpreted consistently.
    
    ### Key changes
    
    * **New API**
    
      * Added a `LengthUnit` enum and `FileSystem.getLengthUnit()` to expose the unit of measure used by `getMaxFileNameLength()` and `getMaxPathLength()`.
      * Added new overloads for `isLegalFileName` and `toLegalFileName` that accept a `Charset`, making conversions between bytes and UTF-16 explicit.
    
    * **Adjusted defaults**
    
      * Reduced the `GENERIC` filesystem defaults:
    
        * File name length → **1020 bytes** (covers 255 UTF-16 characters encoded as up to 3 UTF-8 bytes).
        * Path length → **1 MiB** (covers 32,767 UTF-16 code units, again at 3 UTF-8 bytes each).
    
    * **Testing**
    
      * Added unit tests to validate the new API and updated limits.
---
 src/changes/changes.xml                            |   1 +
 .../java/org/apache/commons/io/FileSystem.java     | 207 ++++++++++++++++++---
 .../java/org/apache/commons/io/FileSystemTest.java | 165 ++++++++++++++--
 3 files changed, 339 insertions(+), 34 deletions(-)

diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index de92deabf..f11043c1f 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -57,6 +57,7 @@ The <action> type attribute can be add,update,fix,remove.
       <action dev="ggregory" type="add"                due-to="Gary Gregory">Add org.apache.commons.io.output.ProxyOutputStream.writeRepeat(byte[], int, int, long).</action>
       <action dev="ggregory" type="add"                due-to="Gary Gregory">Add org.apache.commons.io.output.ProxyOutputStream.writeRepeat(byte[], long).</action>
       <action dev="ggregory" type="add"                due-to="Gary Gregory">Add org.apache.commons.io.output.ProxyOutputStream.writeRepeat(int, long).</action>
+      <action dev="pkarwasz" type="add"                due-to="Piotr P. Karwasz">Add length unit support in FileSystem limits.</action>
       <!-- UPDATE -->
       <action type="update" dev="ggregory"             due-to="Gary Gregory, Dependabot">Bump org.apache.commons:commons-parent from 85 to 87 #774.</action>
       <action type="update" dev="ggregory"             due-to="Gary Gregory">[test] Bump commons-codec:commons-codec from 1.18.0 to 1.19.0.</action>
diff --git a/src/main/java/org/apache/commons/io/FileSystem.java b/src/main/java/org/apache/commons/io/FileSystem.java
index 0e0ddf05a..f24edc488 100644
--- a/src/main/java/org/apache/commons/io/FileSystem.java
+++ b/src/main/java/org/apache/commons/io/FileSystem.java
@@ -17,6 +17,13 @@
 
 package org.apache.commons.io;
 
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.CharacterCodingException;
+import java.nio.charset.Charset;
+import java.nio.charset.CharsetEncoder;
+import java.nio.charset.CoderResult;
+import java.nio.charset.CodingErrorAction;
 import java.util.Arrays;
 import java.util.Locale;
 import java.util.Objects;
@@ -36,7 +43,12 @@ public enum FileSystem {
     /**
      * Generic file system.
      */
-    GENERIC(4096, false, false, Integer.MAX_VALUE, Integer.MAX_VALUE, new int[] { 0 }, new String[] {}, false, false, '/'),
+    GENERIC(4096, false, false, 1020, 1024 * 1024, new int[] {
+            // @formatter:off
+            // ASCII NUL
+            0
+            // @formatter:on
+    }, new String[] {}, false, false, '/', LengthUnit.BYTES),
 
     /**
      * Linux file system.
@@ -48,7 +60,7 @@ public enum FileSystem {
             0,
              '/'
             // @formatter:on
-    }, new String[] {}, false, false, '/'),
+    }, new String[] {}, false, false, '/', LengthUnit.BYTES),
 
     /**
      * MacOS file system.
@@ -61,7 +73,7 @@ public enum FileSystem {
             '/',
              ':'
             // @formatter:on
-    }, new String[] {}, false, false, '/'),
+    }, new String[] {}, false, false, '/', LengthUnit.CHARS),
 
     /**
      * Windows file system.
@@ -78,7 +90,7 @@ public enum FileSystem {
      */
     // @formatter:off
     WINDOWS(4096, false, true,
-            255, 32000, // KEEP THIS ARRAY SORTED!
+            255, 32767, // KEEP THIS ARRAY SORTED!
             new int[] {
                     // KEEP THIS ARRAY SORTED!
                     // ASCII NUL
@@ -95,7 +107,7 @@ public enum FileSystem {
                     "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
                     "LPT\u00b2", "LPT\u00b3", "LPT\u00b9", // Superscript 2 3 1 in that order
                     "NUL", "PRN"
-            }, true, true, '\\');
+            }, true, true, '\\', LengthUnit.CHARS);
     // @formatter:on
 
     /**
@@ -315,6 +327,7 @@ private static String replace(final String path, final char oldChar, final char
     private final boolean supportsDriveLetter;
     private final char nameSeparator;
     private final char nameSeparatorOther;
+    private final LengthUnit lengthUnit;
 
     /**
      * Constructs a new instance.
@@ -329,10 +342,12 @@ private static String replace(final String path, final char oldChar, final char
      * @param reservedFileNamesExtensions TODO
      * @param supportsDriveLetter Whether this file system support driver letters.
      * @param nameSeparator The name separator, '\\' on Windows, '/' on Linux.
+     * @param lengthUnit The unit of measurement for length limits.
      */
     FileSystem(final int blockSize, final boolean caseSensitive, final boolean casePreserving,
         final int maxFileLength, final int maxPathLength, final int[] illegalFileNameChars,
-        final String[] reservedFileNames, final boolean reservedFileNamesExtensions, final boolean supportsDriveLetter, final char nameSeparator) {
+        final String[] reservedFileNames, final boolean reservedFileNamesExtensions, final boolean supportsDriveLetter,
+        final char nameSeparator, final LengthUnit lengthUnit) {
         this.blockSize = blockSize;
         this.maxFileNameLength = maxFileLength;
         this.maxPathLength = maxPathLength;
@@ -345,6 +360,7 @@ private static String replace(final String path, final char oldChar, final char
         this.supportsDriveLetter = supportsDriveLetter;
         this.nameSeparator = nameSeparator;
         this.nameSeparatorOther = FilenameUtils.flipSeparator(nameSeparator);
+        this.lengthUnit = lengthUnit;
     }
 
     /**
@@ -380,23 +396,45 @@ public int[] getIllegalFileNameCodePoints() {
     }
 
     /**
-     * Gets the maximum length for file names. The file name does not include folders.
+     * Gets the maximum length for file names (excluding any folder path).
+     *
+     * <p><strong>Note:</strong> This excludes any folder path. The unit depends on the
+     * filesystem or OS; see {@link #getLengthUnit()} to check whether the value is in
+     * bytes or UTF-16 characters.</p>
      *
-     * @return the maximum length for file names.
+     * @return the maximum file name length.
      */
     public int getMaxFileNameLength() {
         return maxFileNameLength;
     }
 
     /**
-     * Gets the maximum length of the path to a file. This can include folders.
+     * Gets the maximum length for file paths (may include folders).
      *
-     * @return the maximum length of the path to a file.
+     * <p><strong>Note:</strong> This may include folder names as well as the file name.
+     * The unit is the same as {@link #getMaxFileNameLength()} and can be obtained
+     * from {@link #getLengthUnit()}.</p>
+     *
+     * @return the maximum file path length.
      */
     public int getMaxPathLength() {
         return maxPathLength;
     }
 
+    /**
+     * Gets the unit of measurement for length limits.
+     *
+     * <p>Depending on the platform, limits may be expressed in bytes or in UTF-16
+     * characters.</p>
+     *
+     * @return the unit for file name and path length limits.
+     * @since 2.21.0
+     */
+    public LengthUnit getLengthUnit() {
+        return lengthUnit;
+    }
+
+
     /**
      * Gets the name separator, '\\' on Windows, '/' on Linux.
      *
@@ -446,16 +484,42 @@ private boolean isIllegalFileNameChar(final int c) {
     }
 
     /**
-     * Tests if a candidate file name (without a path) such as {@code "filename.ext"} or {@code "filename"} is a
-     * potentially legal file name. If the file name length exceeds {@link #getMaxFileNameLength()}, or if it contains
-     * an illegal character then the check fails.
+     * Tests if a candidate file name (without a path) is a legal file name.
+     *
+     * <p>Takes a file name like {@code "filename.ext"} or {@code "filename"} and checks:</p>
+     * <ul>
+     * <li>if the file name length is legal</li>
+     * <li>if the file name is not a reserved file name</li>
+     * <li>if the file name does not contain illegal characters</li>
+     * </ul>
      *
      * @param candidate
-     *            a candidate file name (without a path) like {@code "filename.ext"} or {@code "filename"}
+     *            A candidate file name (without a path) like {@code "filename.ext"} or {@code "filename"}
      * @return {@code true} if the candidate name is legal
      */
     public boolean isLegalFileName(final CharSequence candidate) {
-        if (candidate == null || candidate.length() == 0 || candidate.length() > maxFileNameLength) {
+        return isLegalFileName(candidate, Charset.defaultCharset());
+    }
+
+    /**
+     * Tests if a candidate file name (without a path) is a legal file name.
+     *
+     * <p>Takes a file name like {@code "filename.ext"} or {@code "filename"} and checks:</p>
+     * <ul>
+     * <li>if the file name length is legal</li>
+     * <li>if the file name is not a reserved file name</li>
+     * <li>if the file name does not contain illegal characters</li>
+     * </ul>
+     *
+     * @param candidate
+     *            A candidate file name (without a path) like {@code "filename.ext"} or {@code "filename"}
+     * @param charset
+     *            The charset to use when the file name length is measured in bytes
+     * @return {@code true} if the candidate name is legal
+     * @since 2.21.0
+     */
+    public boolean isLegalFileName(final CharSequence candidate, final Charset charset) {
+        if (!isLegalFileLength(candidate, charset)) {
             return false;
         }
         if (isReservedFileName(candidate)) {
@@ -504,24 +568,53 @@ public boolean supportsDriveLetter() {
     }
 
     /**
-     * Converts a candidate file name (without a path) like {@code "filename.ext"} or {@code "filename"} to a legal file
-     * name. Illegal characters in the candidate name are replaced by the {@code replacement} character. If the file
-     * name length exceeds {@link #getMaxFileNameLength()}, then the name is truncated to
-     * {@link #getMaxFileNameLength()}.
+     * Converts a candidate file name (without a path) to a legal file name.
+     *
+     * <p>Takes a file name like {@code "filename.ext"} or {@code "filename"} and:</p>
+     * <ul>
+     *     <li>replaces illegal characters by the given replacement character</li>
+     *     <li>truncates the name to {@link #getMaxFileNameLength()} if necessary</li>
+     * </ul>
      *
      * @param candidate
-     *            a candidate file name (without a path) like {@code "filename.ext"} or {@code "filename"}
+     *            A candidate file name (without a path) like {@code "filename.ext"} or {@code "filename"}
      * @param replacement
      *            Illegal characters in the candidate name are replaced by this character
      * @return a String without illegal characters
      */
     public String toLegalFileName(final String candidate, final char replacement) {
+        return toLegalFileName(candidate, replacement, Charset.defaultCharset());
+    }
+
+    /**
+     * Converts a candidate file name (without a path) to a legal file name.
+     *
+     * <p>Takes a file name like {@code "filename.ext"} or {@code "filename"} and:</p>
+     * <ul>
+     *     <li>replaces illegal characters by the given replacement character</li>
+     *     <li>truncates the name to {@link #getMaxFileNameLength()} if necessary</li>
+     * </ul>
+     *
+     * @param candidate
+     *            A candidate file name (without a path) like {@code "filename.ext"} or {@code "filename"}
+     * @param replacement
+     *            Illegal characters in the candidate name are replaced by this character
+     * @param charset
+     *            The charset to use when the file name length is measured in bytes
+     * @return a String without illegal characters
+     * @since 2.21.0
+     */
+    public String toLegalFileName(final String candidate, final char replacement, final Charset charset) {
+        Objects.requireNonNull(candidate, "candidate");
+        if (candidate.isEmpty()) {
+            throw new IllegalArgumentException("The candidate file name is empty");
+        }
         if (isIllegalFileNameChar(replacement)) {
             // %s does not work properly with NUL
             throw new IllegalArgumentException(String.format("The replacement character '%s' cannot be one of the %s illegal characters: %s",
                 replacement == '\0' ? "\\0" : replacement, name(), Arrays.toString(illegalFileNameChars)));
         }
-        final String truncated = candidate.length() > maxFileNameLength ? candidate.substring(0, maxFileNameLength) : candidate;
+        final CharSequence truncated = truncateFileName(candidate, charset);
         final int[] array = truncated.chars().map(i -> isIllegalFileNameChar(i) ? replacement : i).toArray();
         return new String(array, 0, array.length);
     }
@@ -530,4 +623,76 @@ CharSequence trimExtension(final CharSequence cs) {
         final int index = indexOf(cs, '.', 0);
         return index < 0 ? cs : cs.subSequence(0, index);
     }
+
+    private boolean isLegalFileLength(final CharSequence candidate, final Charset charset) {
+        if (candidate == null || candidate.length() == 0) {
+            return false;
+        }
+        if (lengthUnit == LengthUnit.CHARS) {
+            return candidate.length() <= getMaxFileNameLength();
+        }
+        final CharsetEncoder encoder = charset.newEncoder();
+        try {
+            final ByteBuffer buffer = encoder.encode(CharBuffer.wrap(candidate));
+            return buffer.remaining() <= getMaxFileNameLength();
+        } catch (CharacterCodingException e) {
+            // If we can't encode, it's not legal
+            return false;
+        }
+    }
+
+    CharSequence truncateFileName(final CharSequence candidate, final Charset charset) {
+        final int maxFileNameLength = getMaxFileNameLength();
+        // Character-based limit: simple substring if needed.
+        if (lengthUnit == LengthUnit.CHARS) {
+            return candidate.length() <= maxFileNameLength ? candidate : candidate.subSequence(0, maxFileNameLength);
+        }
+
+        // Byte-based limit
+        return truncateByBytes(candidate, charset, maxFileNameLength);
+    }
+
+    static CharSequence truncateByBytes(final CharSequence candidate, final Charset charset, final int maxBytes) {
+        // Byte-based limit
+        final CharsetEncoder encoder = charset.newEncoder()
+                .onMalformedInput(CodingErrorAction.REPORT)
+                .onUnmappableCharacter(CodingErrorAction.REPORT);
+
+        if (!encoder.canEncode(candidate)) {
+            throw new IllegalArgumentException(
+                    "File name contains characters that cannot be encoded with charset " + charset.name());
+        }
+
+        // Fast path: if even the worst-case expansion fits, we're done.
+        if (candidate.length() <= Math.floor(maxBytes / encoder.maxBytesPerChar())) {
+            return candidate;
+        }
+
+        // Slow path: encode into a fixed-size byte buffer.
+        final ByteBuffer out = ByteBuffer.allocate(maxBytes);
+        final CharBuffer in = CharBuffer.wrap(candidate);
+
+        // Encode until the first character that would exceed the byte budget.
+        final CoderResult cr = encoder.encode(in, out, true);
+
+        if (cr.isUnderflow()) {
+            // Entire candidate fit within maxFileNameLength bytes.
+            return candidate;
+        }
+
+        // We ran out of space mid-encode: truncate BEFORE the offending character.
+        return candidate.subSequence(0, in.position());
+    }
+
+    /**
+     * Units of length for the file name and path length limits.
+     *
+     * @since 2.21.0
+     */
+    public enum LengthUnit {
+        /** Length in bytes. */
+        BYTES,
+        /** Length in UTF-16 characters. */
+        CHARS;
+    }
 }
diff --git a/src/test/java/org/apache/commons/io/FileSystemTest.java b/src/test/java/org/apache/commons/io/FileSystemTest.java
index d061a618e..b45deeef2 100644
--- a/src/test/java/org/apache/commons/io/FileSystemTest.java
+++ b/src/test/java/org/apache/commons/io/FileSystemTest.java
@@ -17,21 +17,45 @@
 
 package org.apache.commons.io;
 
+import static java.nio.charset.StandardCharsets.US_ASCII;
+import static java.nio.charset.StandardCharsets.UTF_8;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertFalse;
 import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
 
+import java.io.IOException;
+import java.nio.charset.Charset;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Objects;
+import java.util.stream.Stream;
+
+import org.apache.commons.io.FileSystem.LengthUnit;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.lang3.SystemProperties;
 import org.apache.commons.lang3.SystemUtils;
 import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.condition.EnabledOnOs;
-import org.junit.jupiter.api.condition.OS;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.EnumSource;
+import org.junit.jupiter.params.provider.MethodSource;
 
 /**
  * Tests {@link FileSystem}.
  */
 class FileSystemTest {
 
+    // 255 UTF-8 bytes == 85 UTF-16 chars of 3-byte UTF-8
+    private static final String FILE_NAME_255_BYTES = StringUtils.repeat('★', 85);
+    // 255 UTF-16 chars == 3 * 85 UTF-8 chars
+    private static final String FILE_NAME_255_CHARS = StringUtils.repeat(FILE_NAME_255_BYTES, 3);
+    // 1020 UTF-8 bytes
+    private static final String FILE_NAME_1020_BYTES = StringUtils.repeat(FILE_NAME_255_BYTES, 4);
+
     @Test
     void testGetBlockSize() {
         assertTrue(FileSystem.getCurrent().getBlockSize() >= 0);
@@ -56,20 +80,56 @@ void testGetIllegalFileNameChars() {
         assertNotSame(current.getIllegalFileNameChars(), current.getIllegalFileNameChars());
     }
 
+    @ParameterizedTest
+    @EnumSource(FileSystem.class)
+    void testGetLengthUnit(FileSystem fs) {
+        final LengthUnit expected =
+                fs == FileSystem.WINDOWS || fs == FileSystem.MAC_OSX ? LengthUnit.CHARS : LengthUnit.BYTES;
+        assertEquals(expected, fs.getLengthUnit());
+    }
+
     @Test
-    void testIsLegalName() {
-        for (final FileSystem fs : FileSystem.values()) {
-            assertFalse(fs.isLegalFileName(""), fs.name()); // Empty is always illegal
-            assertFalse(fs.isLegalFileName(null), fs.name()); // null is always illegal
-            assertFalse(fs.isLegalFileName("\0"), fs.name()); // Assume NUL is always illegal
-            assertTrue(fs.isLegalFileName("0"), fs.name()); // Assume simple name always legal
-            for (final String candidate : fs.getReservedFileNames()) {
-                // Reserved file names are not legal
-                assertFalse(fs.isLegalFileName(candidate), candidate);
-            }
+    void testGetNameSeparator() {
+        final FileSystem current = FileSystem.getCurrent();
+        assertEquals(SystemProperties.getFileSeparator(), Character.toString(current.getNameSeparator()));
+    }
+
+    @ParameterizedTest
+    @EnumSource(FileSystem.class)
+    void testIsLegalName(final FileSystem fs) {
+        assertFalse(fs.isLegalFileName(""), fs.name()); // Empty is always illegal
+        assertFalse(fs.isLegalFileName(null), fs.name()); // null is always illegal
+        assertFalse(fs.isLegalFileName("\0"), fs.name()); // Assume NUL is always illegal
+        assertTrue(fs.isLegalFileName("0"), fs.name()); // Assume simple name always legal
+        for (final String candidate : fs.getReservedFileNames()) {
+            // Reserved file names are not legal
+            assertFalse(fs.isLegalFileName(candidate), candidate);
         }
     }
 
+    static Stream<Arguments> testIsLegalName_Length() {
+        return Stream.of(
+                Arguments.of(FileSystem.GENERIC, FILE_NAME_1020_BYTES, UTF_8),
+                Arguments.of(FileSystem.LINUX, FILE_NAME_255_BYTES, UTF_8),
+                Arguments.of(FileSystem.MAC_OSX, FILE_NAME_255_CHARS, UTF_8),
+                Arguments.of(FileSystem.WINDOWS, FILE_NAME_255_CHARS, UTF_8)
+        );
+    }
+
+    @ParameterizedTest
+    @MethodSource
+    void testIsLegalName_Length(FileSystem fs, String nameAtLimit, Charset charset) {
+        assertTrue(fs.isLegalFileName(nameAtLimit, charset), fs.name() + " length at limit");
+        final String nameOverLimit = nameAtLimit + "a";
+        assertFalse(fs.isLegalFileName(nameOverLimit, charset), fs.name() + " length over limit");
+    }
+
+    @Test
+    void testIsLegalName_Encoding() {
+        assertFalse(FileSystem.GENERIC.isLegalFileName(FILE_NAME_255_BYTES, US_ASCII), "US-ASCII cannot represent all chars");
+        assertTrue(FileSystem.GENERIC.isLegalFileName(FILE_NAME_255_BYTES, UTF_8), "UTF-8 can represent all chars");
+    }
+
     @Test
     void testIsReservedFileName() {
         for (final FileSystem fs : FileSystem.values()) {
@@ -80,7 +140,6 @@ void testIsReservedFileName() {
     }
 
     @Test
-    @EnabledOnOs(OS.WINDOWS)
     void testIsReservedFileNameOnWindows() {
         final FileSystem fs = FileSystem.WINDOWS;
         for (final String candidate : fs.getReservedFileNames()) {
@@ -128,6 +187,21 @@ void testSorted() {
         }
     }
 
+    @Test
+    void testMaxNameLength_MatchesRealSystem(@TempDir Path tempDir) {
+        final FileSystem fs = FileSystem.getCurrent();
+        final String fileName = fs.getLengthUnit() == LengthUnit.BYTES ? FILE_NAME_255_BYTES : FILE_NAME_255_CHARS;
+        // OS accepts a maximum length name
+        assertDoesNotThrow(() -> Files.createFile(tempDir.resolve(fileName)), "OS accepts max length name");
+        // OS rejects a too-long name
+        final String tooLongName = fileName + "a";
+        assertThrows(
+                IOException.class, () -> Files.createFile(tempDir.resolve(tooLongName)), "OS rejects too-long name");
+        // Commons IO agrees
+        assertTrue(fs.isLegalFileName(fileName, UTF_8), "Commons IO accepts max length name");
+        assertFalse(fs.isLegalFileName(tooLongName, UTF_8), "Commons IO rejects too-long name");
+    }
+
     @Test
     void testSupportsDriveLetter() {
         assertTrue(FileSystem.WINDOWS.supportsDriveLetter());
@@ -156,5 +230,70 @@ void testToLegalFileNameWindows() {
         for (char i = '0'; i < '9'; i++) {
             assertEquals(i, fs.toLegalFileName(String.valueOf(i), replacement).charAt(0));
         }
+        // Null and empty
+        assertThrows(NullPointerException.class, () -> fs.toLegalFileName(null, '_'));
+        assertThrows(IllegalArgumentException.class, () -> fs.toLegalFileName("", '_'));
+        // Illegal replacement
+        assertThrows(IllegalArgumentException.class, () -> fs.toLegalFileName("test", '\0'));
+        assertThrows(IllegalArgumentException.class, () -> fs.toLegalFileName("test", ':'));
+    }
+
+    static Stream<Arguments> testTruncateFileName() {
+        return Stream.of(
+                Arguments.of(FileSystem.GENERIC, "simple.txt", "simple.txt"),
+                Arguments.of(FileSystem.GENERIC, FILE_NAME_1020_BYTES + ".txt", FILE_NAME_1020_BYTES),
+                Arguments.of(FileSystem.LINUX, "simple.txt", "simple.txt"),
+                Arguments.of(FileSystem.LINUX, FILE_NAME_255_BYTES + ".txt", FILE_NAME_255_BYTES),
+                Arguments.of(FileSystem.MAC_OSX, "simple.txt", "simple.txt"),
+                Arguments.of(FileSystem.MAC_OSX, FILE_NAME_255_CHARS + ".txt", FILE_NAME_255_CHARS),
+                Arguments.of(FileSystem.WINDOWS, "simple.txt", "simple.txt"),
+                Arguments.of(FileSystem.WINDOWS, FILE_NAME_255_CHARS + ".txt", FILE_NAME_255_CHARS));
+    }
+
+    @ParameterizedTest(name = "{index}: {0} truncates {1} to {2}")
+    @MethodSource
+    void testTruncateFileName(FileSystem fs, String input, String expected) {
+        final CharSequence out = fs.truncateFileName(input, UTF_8);
+        assertEquals(expected, out, fs.name());
+    }
+
+    static Stream<Arguments> testTruncateByBytes_Succeeds() {
+        return Stream.of(
+                // ASCII (UTF-8) — fits
+                Arguments.of("ASCII fits (UTF-8)", "hello", UTF_8, 5, "hello"),
+                // ASCII (UTF-8) — truncate
+                Arguments.of("ASCII truncated (UTF-8)", "hello", UTF_8, 4, "hell"),
+                // Empty input
+                Arguments.of("Empty input", "", UTF_8, 10, ""),
+                // Zero budget → empty
+                Arguments.of("Zero-byte limit", "anything", UTF_8, 0, ""),
+                // UTF-8: 2-byte char exact fit
+                Arguments.of("UTF-8: 2-byte char exact fit", "é", UTF_8, 2, "é"),
+                // UTF-8: 2-byte + ASCII; 3 fits both, 2 fits only 2-byte, 1 fits neither
+                Arguments.of("UTF-8: 2-byte + ASCII, both fit", "éa", UTF_8, 3, "éa"),
+                Arguments.of("UTF-8: 2-byte + ASCII, truncate before ASCII", "éa", UTF_8, 2, "é"),
+                Arguments.of("UTF-8: 2-byte + ASCII, truncate all", "éa", UTF_8, 1, ""),
+                // UTF-8: emoji + ASCII; 5 fits both, 4 fits only emoji, 3 fits neither
+                Arguments.of("UTF-8: emoji + ASCII, both fit", "😀a", UTF_8, 5, "😀a"),
+                Arguments.of("UTF-8: emoji + ASCII, truncate before ASCII", "😀a", UTF_8, 4, "😀"),
+                Arguments.of("UTF-8: emoji + ASCII, truncate all", "😀a", UTF_8, 3, ""),
+                // Large limit (fast-path should accept)
+                Arguments.of("Large limit fast-path (UTF-8)", "ok", UTF_8, 8, "ok"));
+    }
+
+    @ParameterizedTest(name = "{index}: {0}")
+    @MethodSource
+    void testTruncateByBytes_Succeeds(String caseName, String input, Charset charset, int maxBytes, String expected) {
+        final CharSequence out = FileSystem.truncateByBytes(input, charset, maxBytes);
+        // If your contract returns null for null input, this still works; otherwise adjust.
+        assertEquals(expected, Objects.toString(out, null), caseName);
+    }
+
+    @Test
+    void testTruncateByBytes_UnmappableAsciiThrows() {
+        final String in = "café"; // contains 'é' (not in ASCII)
+        final IllegalArgumentException ex =
+                assertThrows(IllegalArgumentException.class, () -> FileSystem.truncateByBytes(in, US_ASCII, 100));
+        assertTrue(ex.getMessage().contains(US_ASCII.name()), "ex message contains charset name");
     }
 }