Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Consider a global class registry. #1

Open
typesupply opened this issue Aug 5, 2013 · 0 comments
Open

Consider a global class registry. #1

typesupply opened this issue Aug 5, 2013 · 0 comments

Comments

@typesupply
Copy link
Member

One thing that may help with the memory footprint is to recycle duplicate ClassDef objects. As it is now, every class is fully expanded at all times. This makes sense given that I was trying to keep the code simple instead of worrying about memory when I write this library. Anyway, here's a quick sketch:

import hashlib

class _ClassDefRegistry(object):

    def __init__(self):
        self._classes = {}

    def _makeIdentifier(self, mapping):
        identifier = []
        for name, value in sorted(mapping.items()):
            identifier.append("%s %d" % (name, value))
        identifier = "\n".join(identifier)
        identifier = hashlib.md5(identifier) # this may be over-engineering
        return identifier

    def store(self, mapping):
        identifier = self._makeIdentifier(mapping)
        self._classes[identifier] = mapping
        return identifier

    def __getitem__(self, identifier):
        return self._classes[identifier]


class ClassDef(object):

    __slots__ = ["_identifier", "_classDefRegistry", "_map", "ClassFormat", "Glyphs"]

    def __init__(self, classDefRegistry):
        self._classDefRegistry = classDefRegistry
        self.ClassFormat = None

    def loadFromFontTools(self, classDef):
        self.ClassFormat = classDef.Format
        self._identifier = self._classDefRegistry.store(dict(classDef.classDefs))
        return self

    def __getitem__(self, glyphName):
        return self.Glyphs.get(glyphName, 0)

    def _get_Glyphs(self):
        return self._classDefRegistry[self._identifier]

    Glyphs = property(_get_Glyphs, doc="This is for reference only. Not for use in processing.")


# ----
# Test
# ----

class _Dummy(object):

    def __init__(self):
        self.Format = 0
        self.classDefs = {}


test = _Dummy()
letters = "abcdefghijklmnopqrstuvwxyz"
for i in range(26):
    for j in range(1, 11):
        name = letters[i] * j
        value = len(test.classDefs)
        test.classDefs[name] = value

registry = _ClassDefRegistry()
classDef = ClassDef(registry)
classDef.loadFromFontTools(test)

print classDef.Glyphs
print classDef["mmm"]

This would require some significant structural engineering so that the global registry is passed around as needed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant