Source

pyGAP / game / tools / utils.py

#!/usr/bin/env python
# encoding: utf-8

import re
import shutil
from waflib import Utils

RE_FILENAME = re.compile('^(.*/)?(?:$|(.+?)(\.[^.]*)(?:(\.[^.]*$)|$))')


def get_hash(key):
    '''http://en.wikipedia.org/wiki/Fowler_Noll_Vo_hash'''
    fnv_prime = 0x1000193
    h = 0x811C9DC5
    for i in range(len(key)):
        h *= fnv_prime
        h ^= ord(key[i])
    return h & 0xFFFFFFFF


def filename_info(filename):
    filename = filename.replace('\\', '/')
    result = RE_FILENAME.match(filename)
    filename = ''.join(s for s in result.groups()[:3] if s)
    ext = result.group(3)
    return filename, ext, get_hash(filename)


def has_hash_collision(array):
    hashes = []
    for obj in array:
        h = hash(obj)
        if h in hashes:
            return obj
        else:
            hashes.append(h)
    return None


def remap_chain(bld, chain, *k, **kw):
    tg = bld(source=bld.path.ant_glob(k, kw))
    incl = Utils.to_list(k and k[0] or kw.get('incl', '**'))
    for f in incl:
        tg.mappings['.%s' % f.split('.')[-1]] = chain
    return tg


def copy(task):
    shutil.copy2(task.inputs[0].abspath(), task.outputs[0].abspath())


def compress(task):
    if task.env.zip_module.__name__ == 'lzma':
        task.outputs[0].write(
            task.env.zip_module.compress(task.inputs[0].read('rb'),
                options={'level': task.env.zip_level}), 'wb')
    else:
        task.outputs[0].write(
            task.env.zip_module.compress(
                task.inputs[0].read('rb'),
                task.env.zip_level), 'wb')


def align(offset, size):
    mod = offset % size
    if mod:
        offset += size - mod
    return offset


def pad_file(f, size):
    mod = f.tell() % size
    if mod:
        f.write(b'\0' * (size - mod))


def pad_str(s, offset, size):
    mod = (offset + len(s)) % size
    if mod:
        s = s.ljust(len(s) + size - mod, b'\0')
    return s