1# Support code for building a C extension with blake2 files
2#
3# Copyright (c) 2016-present, Gregory Szorc (original code for zstd)
4#               2017-present, Thomas Waldmann (mods to make it more generic, code for blake2)
5# All rights reserved.
6#
7# This software may be modified and distributed under the terms
8# of the BSD license. See the LICENSE file for details.
9
10import os
11
12# b2 files, structure as seen in BLAKE2 (reference implementation) project repository:
13
14b2_sources = [
15    'ref/blake2b-ref.c',
16]
17
18b2_includes = [
19    'ref',
20]
21
22
23def b2_system_prefix(prefixes):
24    for prefix in prefixes:
25        filename = os.path.join(prefix, 'include', 'blake2.h')
26        if os.path.exists(filename):
27            with open(filename, 'rb') as fd:
28                if b'blake2b_init' in fd.read():
29                    return prefix
30
31
32def b2_ext_kwargs(bundled_path, system_prefix=None, system=False, **kwargs):
33    """amend kwargs with b2 stuff for a distutils.extension.Extension initialization.
34
35    bundled_path: relative (to this file) path to the bundled library source code files
36    system_prefix: where the system-installed library can be found
37    system: True: use the system-installed shared library, False: use the bundled library code
38    kwargs: distutils.extension.Extension kwargs that should be amended
39    returns: amended kwargs
40    """
41    def multi_join(paths, *path_segments):
42        """apply os.path.join on a list of paths"""
43        return [os.path.join(*(path_segments + (path, ))) for path in paths]
44
45    use_system = system and system_prefix is not None
46
47    sources = kwargs.get('sources', [])
48    if not use_system:
49        sources += multi_join(b2_sources, bundled_path)
50
51    include_dirs = kwargs.get('include_dirs', [])
52    if use_system:
53        include_dirs += multi_join(['include'], system_prefix)
54    else:
55        include_dirs += multi_join(b2_includes, bundled_path)
56
57    library_dirs = kwargs.get('library_dirs', [])
58    if use_system:
59        library_dirs += multi_join(['lib'], system_prefix)
60
61    libraries = kwargs.get('libraries', [])
62    if use_system:
63        libraries += ['b2', ]
64
65    extra_compile_args = kwargs.get('extra_compile_args', [])
66    if not use_system:
67        extra_compile_args += []  # not used yet
68
69    ret = dict(**kwargs)
70    ret.update(dict(sources=sources, extra_compile_args=extra_compile_args,
71                    include_dirs=include_dirs, library_dirs=library_dirs, libraries=libraries))
72    return ret
73