@Restricted(NoExternalUse.class)
    public static Set<PosixFilePermission> modeToPermissions(int mode) throws IOException {
         // Anything larger is a file type, not a permission.
        int PERMISSIONS_MASK = 07777;
        // setgid/setuid/sticky are not supported.
        int MAX_SUPPORTED_MODE = 0777;
        mode = mode & PERMISSIONS_MASK;
        if ((mode & MAX_SUPPORTED_MODE) != mode) {
            throw new IOException("Invalid mode: " + mode);
        }
        PosixFilePermission[] allPermissions = PosixFilePermission.values();
        Set<PosixFilePermission> result = EnumSet.noneOf(PosixFilePermission.class);
        for (int i = 0; i < allPermissions.length; i++) {
            if ((mode & 1) == 1) {
                result.add(allPermissions[allPermissions.length - i - 1]);
            }
            mode >>= 1;
        }
        return result;
    }
@Test
    public void testModeToPermissions() throws Exception {
        assertEquals(PosixFilePermissions.fromString("rwxrwxrwx"), Util.modeToPermissions(0777));
        assertEquals(PosixFilePermissions.fromString("rwxr-xrwx"), Util.modeToPermissions(0757));
        assertEquals(PosixFilePermissions.fromString("rwxr-x---"), Util.modeToPermissions(0750));
        assertEquals(PosixFilePermissions.fromString("r-xr-x---"), Util.modeToPermissions(0550));
        assertEquals(PosixFilePermissions.fromString("r-xr-----"), Util.modeToPermissions(0540));
        assertEquals(PosixFilePermissions.fromString("--xr-----"), Util.modeToPermissions(0140));
        assertEquals(PosixFilePermissions.fromString("--xr---w-"), Util.modeToPermissions(0142));
        assertEquals(PosixFilePermissions.fromString("--xr--rw-"), Util.modeToPermissions(0146));
        assertEquals(PosixFilePermissions.fromString("-wxr--rw-"), Util.modeToPermissions(0346));
        assertEquals(PosixFilePermissions.fromString("---------"), Util.modeToPermissions(0000));

        assertEquals("Non-permission bits should be ignored", PosixFilePermissions.fromString("r-xr-----"), Util.modeToPermissions(0100540));

        Exception e = Assert.assertThrows(Exception.class, () -> Util.modeToPermissions(01777));
        assertThat(e.getMessage(), startsWith("Invalid mode"));
    }