import multiprocessing
import ctypes

class SharedMemEnum(object):
    def __init__(self, enum, lock=True):
        self._enum = enum
        self._sm = multiprocessing.Value('H', lock=lock)

    @property
    def index(self):
        return self._sm.value

    @index.setter
    def index(self, index):
        self._sm.value = index

    @property
    def value(self):
        return self._enum[self._sm.value]

    @value.setter
    def value(self, value):
        try:
            self._sm.value = self._enum.index(value)
        except ValueError:
            raise ValueError("unknown SharedMemEnum index: %s" % value)


class SharedMemString(object):
    def __init__(self, size=40, lock=True):
        self._size = size
        self._sm = multiprocessing.Array(ctypes.c_char, size, lock=lock)
        self.set_value()

    @property
    def raw(self):
        return self._sm.raw

    @property
    def value(self):
        return self._sm.value.decode()

    @value.setter
    def value(self, value):
        self.set_value(value)

    def set_value(self, value=''):
        value = str(value)
        size = self._size
        self._sm.value = '{:\0<{size}}'.format(value[:size], size=size).encode()
