I implemented a virtual file system library with POSIX file mode representation.
Any suggestions regarding optimization are welcome.
"""POSIX file system library."""
from collections import namedtuple
__all__ = ['PosixPermission', 'PosixMode']
MIN_PERM = 0b000
MAX_PERM = 0b111
DEF_PERM = 0b110 # rw-
MIN_MODE = 0o000
MAX_MODE = 0o777
DEF_MODE = 0o640
class PosixPermission(namedtuple('PosixPermission', 'read write execute')):
"""POSIX file permissions."""
@classmethod
def from_int(cls, perm=DEF_PERM):
"""Creates the file permissions from the respective integer value."""
if MIN_PERM <= perm <= MAX_PERM:
return cls(bool(perm & 4), bool(perm & 2), bool(perm & 1))
raise ValueError('Permission value must be between {} and {}.'.format(
MIN_PERM, MAX_PERM))
def __int__(self):
"""Returns the integer value of the file permission."""
return (self.read and 4) + (self.write and 2) + (self.execute and 1)
def __str__(self):
"""Returns binary representation of the file permission."""
return ''.join(map(
lambda perm: perm or '-',
(self.read and 'r', self.write and 'w', self.execute and 'x')))
class PosixMode(namedtuple('PosixMode', 'user group other')):
"""POSIX file mode."""
@classmethod
def from_int(cls, mode=DEF_MODE):
"""Creates the file mode from the respective integer value."""
if MIN_MODE <= mode <= MAX_MODE:
return cls(
PosixPermission.from_int(mode >> 6 & 7),
PosixPermission.from_int(mode >> 3 & 7),
PosixPermission.from_int(mode & 7))
raise ValueError('File mode must be between {} and {}.'.format(
oct(MIN_MODE), oct(MAX_MODE)))
def __int__(self):
"""Returns the integer value of the file mode."""
return (int(self.user) << 6) + (int(self.group) << 3) + int(self.other)
def __str__(self):
"""Returns the octal representation of the file mode."""
return ''.join((str(self.user), str(self.group), str(self.other)))