diff options
author | Edoardo La Greca | 2025-08-10 16:23:27 +0200 |
---|---|---|
committer | Edoardo La Greca | 2025-08-10 16:23:27 +0200 |
commit | 976684b04761c3d3a7e9df056b520ead816855c1 (patch) | |
tree | 47959e6c6ed9e492c170755dc4e33b0e94bdf8cc | |
parent | 9cb11864e2bd698874ec35af8d75b18d9d18217f (diff) |
add another secondary constructor to FilePermissions to read permissions from bytes
-rw-r--r-- | src/main/kotlin/FilePermissions.kt | 31 |
1 files changed, 29 insertions, 2 deletions
diff --git a/src/main/kotlin/FilePermissions.kt b/src/main/kotlin/FilePermissions.kt index dbb9dc4..ce25d23 100644 --- a/src/main/kotlin/FilePermissions.kt +++ b/src/main/kotlin/FilePermissions.kt @@ -23,6 +23,8 @@ class FilePermissions { */ val isDirectory: Boolean + private val DIRECTORY_BIT: UInt = 0x80000000u + enum class Permissions(val bits: UByte) { READ(0x4u), WRITE(0x2u), @@ -30,7 +32,16 @@ class FilePermissions { READ_WRITE(READ.bits.or(WRITE.bits)), READ_EXECUTE(READ.bits.or(EXECUTE.bits)), WRITE_EXECUTE(WRITE.bits.or(EXECUTE.bits)), - READ_WRITE_EXECUTE(READ.bits.or(WRITE.bits.or(EXECUTE.bits))) + READ_WRITE_EXECUTE(READ.bits.or(WRITE.bits.or(EXECUTE.bits))); + + companion object { + /** + * Obtain a [Permissions] instance by matching its value. + * + * @throws NoSuchElementException if no such element has the provided value. + */ + fun fromByte(bits: UByte) = Permissions.entries.first { it.bits == bits } + } } /** @@ -49,6 +60,22 @@ class FilePermissions { } /** + * Constructor for raw file permission data. Only the first 4 elements are read. + * + * @param raw The raw file permission data. + * @throws IllegalArgumentException if [raw] does not have at least 4 elements. + */ + constructor(raw: List<UByte>) { + require(raw.size >= 4) + val raw = raw.slice(0..4) + val dirValue = raw[0].toUInt().xor(this.DIRECTORY_BIT) + this.isDirectory = dirValue > 0u + this.userPerms = Permissions.fromByte(raw[1]) + this.groupPerms = Permissions.fromByte(raw[2]) + this.elsePerms = Permissions.fromByte(raw[3]) + } + + /** * Turn the permissions described by the [FilePermissions] fields into a permission integer (4 bytes). */ fun toPermissionInt(): UInt { @@ -58,7 +85,7 @@ class FilePermissions { perms.or(permFileds[i].bits.toUInt().shl(8 * (permFileds.size - 1 - i))) } if (isDirectory) { - perms.or(0x80000000u) + perms.or(this.DIRECTORY_BIT) } return perms } |