-- Well known name table entries. -- Copyright (C) 2002, 2003, 2004, 2005 Tristan Gingold -- -- GHDL is free software; you can redistribute it and/or modify it under -- the terms of the GNU General Public License as published by the Free -- Software Foundation; either version 2, or (at your option) any later -- version. -- -- GHDL is distributed in the hope that it will be useful, but WITHOUT ANY -- WARRANTY; without even the implied warranty of MERCHANTABILITY or -- FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- for more details. -- -- You should have received a copy of the GNU General Public License -- along with GHDL; see the file COPYING. If not, write to the Free -- Software Foundation, 59 Temple Place - Suite 330, Boston, MA -- 02111-1307, USA. with Types; use Types; -- Note: since all identifiers declared in this package begins with either -- std_names or name, this package is expected to be use'd. package Std_Names is -- Predefined names. Name_First_Character : constant Name_Id := 1; Name_Last_Character : constant Name_Id := Name_First_Character + Character'Pos (Character'Last) - Character'Pos (Character'First); subtype Name_Characters is Name_Id range Name_First_Character .. Name_Last_Character; Name_First_Keyword : constant Name_Id := Name_Last_Character + 1; -- Word operators. Name_Mod : constant Name_Id := Name_First_Keyword + 000; Name_Rem : constant Name_Id := Name_First_Keyword + 001; Name_And : constant Name_Id := Name_First_Keyword + 002; Name_Or : constant Name_Id := Name_First_Keyword + 003; Name_Xor : constant Name_Id := Name_First_Keyword + 004; Name_Nand : constant Name_Id := Name_First_Keyword + 005; Name_Nor : constant Name_Id := Name_First_Keyword + 006; Name_Abs : constant Name_Id := Name_First_Keyword + 007; Name_Not : constant Name_Id := Name_First_Keyword + 008; subtype Name_Logical_Operators is Name_Id range Name_And .. Name_Nor; subtype Name_Word_Operators is Name_Id range Name_Mod .. Name_Not; Name_Access : constant Name_Id := Name_First_Keyword + 009; Name_After : constant Name_Id := Name_First_Keyword + 010; Name_Alias : constant Name_Id := Name_First_Keyword + 011; Name_All : constant Name_Id := Name_First_Keyword + 012; Name_Architecture : constant Name_Id := Name_First_Keyword + 013; Name_Array : constant Name_Id := Name_First_Keyword + 014; Name_Assert : constant Name_Id := Name_First_Keyword + 015; Name_Attribute : constant Name_Id := Name_First_Keyword + 016; Name_Begin : constant Name_Id := Name_First_Keyword + 017; Name_Block : constant Name_Id := Name_First_Keyword + 018; Name_Body : constant Name_Id := Name_First_Keyword + 019; Name_Buffer : constant Name_Id := Name_First_Keyword + 020; Name_Bus : constant Name_Id := Name_First_Keyword + 021; Name_Case : constant Name_Id := Name_First_Keyword + 022; Name_Component : constant Name_Id := Name_First_Keyword + 023; Name_Configuration : constant Name_Id := Name_First_Keyword + 024; Name_Constant : constant Name_Id := Name_First_Keyword + 025; Name_Disconnect : constant Name_Id := Name_First_Keyword + 026; Name_Downto : constant Name_Id := Name_First_Keyword + 027; Name_Else : constant Name_Id := Name_First_Keyword + 028; Name_Elsif : constant Name_Id := Name_First_Keyword + 029; Name_End : constant Name_Id := Name_First_Keyword + 030; Name_Entity : constant Name_Id := Name_First_Keyword + 031; Name_Exit : constant Name_Id := Name_First_Keyword + 032; Name_File : constant Name_Id := Name_First_Keyword + 033; Name_For : constant Name_Id := Name_First_Keyword + 034; Name_Function : constant Name_Id := Name_First_Keyword + 035; Name_Generate : constant Name_Id := Name_First_Keyword + 036; Name_Generic : constant Name_Id := Name_First_Keyword + 037; Name_Guarded : constant Name_Id := Name_First_Keyword + 038; Name_If : constant Name_Id := Name_First_Keyword + 039; Name_In : constant Name_Id := Name_First_Keyword + 040; Name_Inout : constant Name_Id := Name_First_Keyword + 041; Name_Is : constant Name_Id := Name_First_Keyword + 042; Name_Label : constant Name_Id := Name_First_Keyword + 043; Name_Library : constant Name_Id := Name_First_Keyword + 044; Name_Linkage : constant Name_Id := Name_First_Keyword + 045; Name_Loop : constant Name_Id := Name_First_Keyword + 046; Name_Map : constant Name_Id := Name_First_Keyword + 047; Name_New : constant Name_Id := Name_First_Keyword + 048; Name_Next : constant Name_Id := Name_First_Keyword + 049; Name_Null : constant Name_Id := Name_First_Keyword + 050; Name_Of : constant Name_Id := Name_First_Keyword + 051; Name_On : constant Name_Id := Name_First_Keyword + 052; Name_Open : constant Name_Id := Name_First_Keyword + 053; Name_Others : constant Name_Id := Name_First_Keyword + 054; Name_Out : constant Name_Id := Name_First_Keyword + 055; Name_Package : constant Name_Id := Name_First_Keyword + 056; Name_Port : constant Name_Id := Name_First_Keyword + 057; Name_Procedure : constant Name_Id := Name_First_Keyword + 058; Name_Process : constant Name_Id := Name_First_Keyword + 059; Name_Range : constant Name_Id := Name_First_Keyword + 060; Name_Record : constant Name_Id := Name_First_Keyword + 061; Name_Register : constant Name_Id := Name_First_Keyword + 062; Name_Report : constant Name_Id := Name_First_Keyword + 063; Name_Return : constant Name_Id := Name_First_Keyword + 064; Name_Select : constant Name_Id := Name_First_Keyword + 065; Name_Severity : constant Name_Id := Name_First_Keyword + 066; Name_Signal : constant Name_Id := Name_First_Keyword + 067; Name_Subtype : constant Name_Id := Name_First_Keyword + 068; Name_Then : constant Name_Id := Name_First_Keyword + 069; Name_To : constant Name_Id := Name_First_Keyword + 070; Name_Transport : constant Name_Id := Name_First_Keyword + 071; Name_Type : constant Name_Id := Name_First_Keyword + 072; Name_Units : constant Name_Id := Name_First_Keyword + 073; Name_Until : constant Name_Id := Name_First_Keyword + 074; Name_Use : constant Name_Id := Name_First_Keyword + 075; Name_Variable : constant Name_Id := Name_First_Keyword + 076; Name_Wait : constant Name_Id := Name_First_Keyword + 077; Name_When : constant Name_Id := Name_First_Keyword + 078; Name_While : constant Name_Id := Name_First_Keyword + 079; Name_With : constant Name_Id := Name_First_Keyword + 080; Name_Last_Vhdl87 : constant Name_Id := Name_With; subtype Name_Id_Vhdl87_Reserved_Words is Name_Id range Name_First_Keyword .. Name_With; -- VHDL93 reserved words. Name_Xnor : constant Name_Id := Name_First_Keyword + 081; Name_Group : constant Name_Id := Name_First_Keyword + 082; Name_Impure : constant Name_Id := Name_First_Keyword + 083; Name_Inertial : constant Name_Id := Name_First_Keyword + 084; Name_Literal : constant Name_Id := Name_First_Keyword + 085; Name_Postponed : constant Name_Id := Name_First_Keyword + 086; Name_Pure : constant Name_Id := Name_First_Keyword + 087; Name_Reject : constant Name_Id := Name_First_Keyword + 088; Name_Shared : constant Name_Id := Name_First_Keyword + 089; Name_Unaffected : constant Name_Id := Name_First_Keyword + 090; Name_Sll : constant Name_Id := Name_First_Keyword + 091; Name_Sla : constant Name_Id := Name_First_Keyword + 092; Name_Sra : constant Name_Id := Name_First_Keyword + 093; Name_Srl : constant Name_Id := Name_First_Keyword + 094; Name_Rol : constant Name_Id := Name_First_Keyword + 095; Name_Ror : constant Name_Id := Name_First_Keyword + 096; subtype Name_Shift_Operators is Name_Id range Name_Sll .. Name_Ror; Name_Last_Vhdl93 : constant Name_Id := Name_Ror; subtype Name_Id_Vhdl93_Reserved_Words is Name_Id range Name_Xnor .. Name_Ror; Name_Protected : constant Name_Id := Name_First_Keyword + 097; Name_Last_Vhdl00 : constant Name_Id := Name_Protected; subtype Name_Id_Vhdl00_Reserved_Words is Name_Id range Name_Protected .. Name_Protected; Name_Context : constant Name_Id := Name_First_Keyword + 098; Name_Last_Vhdl08 : constant Name_Id := Name_Context; subtype Name_Id_Vhdl08_Reserved_Words is Name_Id range Name_Context .. Name_Context; Name_First_Ams_Keyword : constant Name_Id := Name_Last_Vhdl08 + 1; Name_Across : constant Name_Id := Name_First_Ams_Keyword + 000; Name_Break : constant Name_Id := Name_First_Ams_Keyword + 001; Name_Limit : constant Name_Id := Name_First_Ams_Keyword + 002; Name_Nature : constant Name_Id := Name_First_Ams_Keyword + 003; Name_Noise : constant Name_Id := Name_First_Ams_Keyword + 004; Name_Procedural : constant Name_Id := Name_First_Ams_Keyword + 005; Name_Quantity : constant Name_Id := Name_First_Ams_Keyword + 006; Name_Reference : constant Name_Id := Name_First_Ams_Keyword + 007; Name_Spectrum : constant Name_Id := Name_First_Ams_Keyword + 008; Name_Subnature : constant Name_Id := Name_First_Ams_Keyword + 009; Name_Terminal : constant Name_Id := Name_First_Ams_Keyword + 010; Name_Through : constant Name_Id := Name_First_Ams_Keyword + 011; Name_Tolerance : constant Name_Id := Name_First_Ams_Keyword + 012; Name_Last_AMS_Vhdl : constant Name_Id := Name_Tolerance; subtype Name_Id_AMS_Reserved_Words is Name_Id range Name_Across .. Name_Tolerance; Name_Last_Keyword : constant Name_Id := Name_Tolerance; subtype Name_Id_Keywords is Name_Id range Name_First_Keyword .. Name_Last_Keyword; Name_First_Operator : constant Name_Id := Name_Last_Keyword + 1; Name_Op_Equality : constant Name_Id := Name_First_Operator + 000; Name_Op_Inequality : constant Name_Id := Name_First_Operator + 001; Name_Op_Less : constant Name_Id := Name_First_Operator + 002; Name_Op_Less_Equal : constant Name_Id := Name_First_Operator + 003; Name_Op_Greater : constant Name_Id := Name_First_Operator + 004; Name_Op_Greater_Equal : constant Name_Id := Name_First_Operator + 5; Name_Op_Plus : constant Name_Id := Name_First_Operator + 006; Name_Op_Minus : constant Name_Id := Name_First_Operator + 007; Name_Op_Mul : constant Name_Id := Name_First_Operator + 008; Name_Op_Div : constant Name_Id := Name_First_Operator + 009; Name_Op_Exp : constant Name_Id := Name_First_Operator + 010; Name_Op_Concatenation : constant Name_Id := Name_First_Operator + 011; Name_Op_Condition : constant Name_Id := Name_First_Operator + 012; Name_Op_Match_Equality : constant Name_Id := Name_First_Operator + 013; Name_Op_Match_Inequality : constant Name_Id := Name_First_Operator + 014; Name_Op_Match_Less : constant Name_Id := Name_First_Operator + 015; Name_Op_Match_Less_Equal : constant Name_Id := Name_First_Operator + 016; Name_Op_Match_Greater : constant Name_Id := Name_First_Operator + 017; Name_Op_Match_Greater_Equal : constant Name_Id := Name_First_Operator + 018; Name_Last_Operator : constant Name_Id := Name_Op_Match_Greater_Equal; subtype Name_Relational_Operators is Name_Id range Name_Op_Equality .. Name_Op_Greater_Equal; -- List of symbolic operators (available as string). subtype Name_Id_Operators is Name_Id range Name_First_Operator .. Name_Last_Operator; Name_First_Attribute : constant Name_Id := Name_Last_Operator + 1; Name_Base : constant Name_Id := Name_First_Attribute + 000; Name_Left : constant Name_Id := Name_First_Attribute + 001; Name_Right : constant Name_Id := Name_First_Attribute + 002; Name_High : constant Name_Id := Name_First_Attribute + 003; Name_Low : constant Name_Id := Name_First_Attribute + 004; Name_Pos : constant Name_Id := Name_First_Attribute + 005; Name_Val : constant Name_Id := Name_First_Attribute + 006; Name_Succ : constant Name_Id := Name_First_Attribute + 007; Name_Pred : constant Name_Id := Name_First_Attribute + 008; Name_Leftof : constant Name_Id := Name_First_Attribute + 009; Name_Rightof : constant Name_Id := Name_First_Attribute + 010; Name_Reverse_Range : constant Name_Id := Name_First_Attribute + 011; Name_Length : constant Name_Id := Name_First_Attribute + 012; Name_Delayed : constant Name_Id := Name_First_Attribute + 013; Name_Stable : constant Name_Id := Name_First_Attribute + 014; Name_Quiet : constant Name_Id := Name_First_Attribute + 015; Name_Transaction : constant Name_Id := Name_First_Attribute + 016; Name_Event : constant Name_Id := Name_First_Attribute + 017; Name_Active : constant Name_Id := Name_First_Attribute + 018; Name_Last_Event : constant Name_Id := Name_First_Attribute + 019; Name_Last_Active : constant Name_Id := Name_First_Attribute + 020; Name_Last_Value : constant Name_Id := Name_First_Attribute + 021; Name_Last_Attribute : constant Name_Id := Name_Last_Value; subtype Name_Id_Attributes is Name_Id range Name_First_Attribute ..Name_Last_Attribute; Name_First_Vhdl87_Attribute : constant Name_Id := Name_Last_Value + 1; Name_Behavior : constant Name_Id := Name_First_Attribute + 022; Name_Structure : constant Name_Id := Name_First_Attribute + 023; Name_Last_Vhdl87_Attribute : constant Name_Id := Name_Structure; subtype Name_Id_Vhdl87_Attributes is Name_Id range Name_First_Vhdl87_Attribute ..Name_Last_Vhdl87_Attribute; Name_First_Vhdl93_Attribute : constant Name_Id := Name_Structure + 1; Name_Ascending : constant Name_Id := Name_First_Attribute + 024; Name_Image : constant Name_Id := Name_First_Attribute + 025; Name_Value : constant Name_Id := Name_First_Attribute + 026; Name_Driving : constant Name_Id := Name_First_Attribute + 027; Name_Driving_Value : constant Name_Id := Name_First_Attribute + 028; Name_Simple_Name : constant Name_Id := Name_First_Attribute + 029; Name_Instance_Name : constant Name_Id := Name_First_Attribute + 030; Name_Path_Name : constant Name_Id := Name_First_Attribute + 031; Name_Last_Vhdl93_Attribute : constant Name_Id := Name_Path_Name; subtype Name_Id_Vhdl93_Attributes is Name_Id range Name_First_Vhdl93_Attribute ..Name_Last_Vhdl93_Attribute; Name_First_AMS_Attribute : constant Name_Id := Name_Last_Vhdl93_Attribute + 1; Name_Contribution : constant Name_Id := Name_First_AMS_Attribute + 000; Name_Dot : constant Name_Id := Name_First_AMS_Attribute + 001; Name_Integ : constant Name_Id := Name_First_AMS_Attribute + 002; Name_Above : constant Name_Id := Name_First_AMS_Attribute + 003; Name_ZOH : constant Name_Id := Name_First_AMS_Attribute + 004; Name_LTF : constant Name_Id := Name_First_AMS_Attribute + 005; Name_ZTF : constant Name_Id := Name_First_AMS_Attribute + 006; Name_Ramp : constant Name_Id := Name_First_AMS_Attribute + 007; Name_Slew : constant Name_Id := Name_First_AMS_Attribute + 008; Name_Last_AMS_Attribute : constant Name_Id := Name_Slew; subtype Name_Id_Name_Attributes is Name_Id range Name_Simple_Name .. Name_Path_Name; -- Names used in std.standard package. Name_First_Standard : constant Name_Id := Name_Last_AMS_Attribute + 1; Name_Std : constant Name_Id := Name_First_Standard + 000; Name_Standard : constant Name_Id := Name_First_Standard + 001; Name_Boolean : constant Name_Id := Name_First_Standard + 002; Name_False : constant Name_Id := Name_First_Standard + 003; Name_True : constant Name_Id := Name_First_Standard + 004; Name_Bit : constant Name_Id := Name_First_Standard + 005; Name_Character : constant Name_Id := Name_First_Standard + 006; Name_Severity_Level : constant Name_Id := Name_First_Standard + 007; Name_Note : constant Name_Id := Name_First_Standard + 008; Name_Warning : constant Name_Id := Name_First_Standard + 009; Name_Error : constant Name_Id := Name_First_Standard + 010; Name_Failure : constant Name_Id := Name_First_Standard + 011; Name_Universal_Integer : constant Name_Id := Name_First_Standard + 012; Name_Universal_Real : constant Name_Id := Name_First_Standard + 013; Name_Convertible_Integer : constant Name_Id := Name_First_Standard + 014; Name_Convertible_Real : constant Name_Id := Name_First_Standard + 015; Name_Integer : constant Name_Id := Name_First_Standard + 016; Name_Real : constant Name_Id := Name_First_Standard + 017; Name_Time : constant Name_Id := Name_First_Standard + 018; Name_Fs : constant Name_Id := Name_First_Standard + 019; Name_Ps : constant Name_Id := Name_First_Standard + 020; Name_Ns : constant Name_Id := Name_First_Standard + 021; Name_Us : constant Name_Id := Name_First_Standard + 022; Name_Ms : constant Name_Id := Name_First_Standard + 023; Name_Sec : constant Name_Id := Name_First_Standard + 024; Name_Min : constant Name_Id := Name_First_Standard + 025; Name_Hr : constant Name_Id := Name_First_Standard + 026; Name_Delay_Length : constant Name_Id := Name_First_Standard + 027; Name_Now : constant Name_Id := Name_First_Standard + 028; Name_Natural : constant Name_Id := Name_First_Standard + 029; Name_Positive : constant Name_Id := Name_First_Standard + 030; Name_String : constant Name_Id := Name_First_Standard + 031; Name_Bit_Vector : constant Name_Id := Name_First_Standard + 032; Name_File_Open_Kind : constant Name_Id := Name_First_Standard + 033; Name_Read_Mode : constant Name_Id := Name_First_Standard + 034; Name_Write_Mode : constant Name_Id := Name_First_Standard + 035; Name_Append_Mode : constant Name_Id := Name_First_Standard + 036; Name_File_Open_Status : constant Name_Id := Name_First_Standard + 037; Name_Open_Ok : constant Name_Id := Name_First_Standard + 038; Name_Status_Error : constant Name_Id := Name_First_Standard + 039; Name_Name_Error : constant Name_Id := Name_First_Standard + 040; Name_Mode_Error : constant Name_Id := Name_First_Standard + 041; Name_Foreign : constant Name_Id := Name_First_Standard + 042; -- Added by VHDL 08 Name_Boolean_Vector : constant Name_Id := Name_First_Standard + 043; Name_To_Bstring : constant Name_Id := Name_First_Standard + 044; Name_To_Binary_String : constant Name_Id := Name_First_Standard + 045; Name_To_Ostring : constant Name_Id := Name_First_Standard + 046; Name_To_Octal_String : constant Name_Id := Name_First_Standard + 047; Name_To_Hstring : constant Name_Id := Name_First_Standard + 048; Name_To_Hex_String : constant Name_Id := Name_First_Standard + 049; Name_Integer_Vector : constant Name_Id := Name_First_Standard + 050; Name_Real_Vector : constant Name_Id := Name_First_Standard + 051; Name_Time_Vector : constant Name_Id := Name_First_Standard + 052; Name_Digits : constant Name_Id := Name_First_Standard + 053; Name_Format : constant Name_Id := Name_First_Standard + 054; Name_Unit : constant Name_Id := Name_First_Standard + 055; -- Added by AMS vhdl. Name_Domain_Type : constant Name_Id := Name_First_Standard + 056; Name_Quiescent_Domain : constant Name_Id := Name_First_Standard + 057; Name_Time_Domain : constant Name_Id := Name_First_Standard + 058; Name_Frequency_Domain : constant Name_Id := Name_First_Standard + 059; Name_Domain : constant Name_Id := Name_First_Standard + 060; Name_Frequency : constant Name_Id := Name_First_Standard + 061; Name_Last_Standard : constant Name_Id := Name_Frequency; Name_First_Charname : constant Name_Id := Name_Last_Standard + 1; Name_Nul : constant Name_Id := Name_First_Charname + 00; Name_Soh : constant Name_Id := Name_First_Charname + 01; Name_Stx : constant Name_Id := Name_First_Charname + 02; Name_Etx : constant Name_Id := Name_First_Charname + 03; Name_Eot : constant Name_Id := Name_First_Charname + 04; Name_Enq : constant Name_Id := Name_First_Charname + 05; Name_Ack : constant Name_Id := Name_First_Charname + 06; Name_Bel : constant Name_Id := Name_First_Charname + 07; Name_Bs : constant Name_Id := Name_First_Charname + 08; Name_Ht : constant Name_Id := Name_First_Charname + 09; Name_Lf : constant Name_Id := Name_First_Charname + 10; Name_Vt : constant Name_Id := Name_First_Charname + 11; Name_Ff : constant Name_Id := Name_First_Charname + 12; Name_Cr : constant Name_Id := Name_First_Charname + 13; Name_So : constant Name_Id := Name_First_Charname + 14; Name_Si : constant Name_Id := Name_First_Charname + 15; Name_Dle : constant Name_Id := Name_First_Charname + 16; Name_Dc1 : constant Name_Id := Name_First_Charname + 17; Name_Dc2 : constant Name_Id := Name_First_Charname + 18; Name_Dc3 : constant Name_Id := Name_First_Charname + 19; Name_Dc4 : constant Name_Id := Name_First_Charname + 20; Name_Nak : constant Name_Id := Name_First_Charname + 21; Name_Syn : constant Name_Id := Name_First_Charname + 22; Name_Etb : constant Name_Id := Name_First_Charname + 23; Name_Can : constant Name_Id := Name_First_Charname + 24; Name_Em : constant Name_Id := Name_First_Charname + 25; Name_Sub : constant Name_Id := Name_First_Charname + 26; Name_Esc : constant Name_Id := Name_First_Charname + 27; Name_Fsp : constant Name_Id := Name_First_Charname + 28; Name_Gsp : constant Name_Id := Name_First_Charname + 29; Name_Rsp : constant Name_Id := Name_First_Charname + 30; Name_Usp : constant Name_Id := Name_First_Charname + 31; Name_Del : constant Name_Id := Name_First_Charname + 32; Name_C128 : constant Name_Id := Name_First_Charname + 33; Name_C129 : constant Name_Id := Name_First_Charname + 34; Name_C130 : constant Name_Id := Name_First_Charname + 35; Name_C131 : constant Name_Id := Name_First_Charname + 36; Name_C132 : constant Name_Id := Name_First_Charname + 37; Name_C133 : constant Name_Id := Name_First_Charname + 38; Name_C134 : constant Name_Id := Name_First_Charname + 39; Name_C135 : constant Name_Id := Name_First_Charname + 40; Name_C136 : constant Name_Id := Name_First_Charname + 41; Name_C137 : constant Name_Id := Name_First_Charname + 42; Name_C138 : constant Name_Id := Name_First_Charname + 43; Name_C139 : constant Name_Id := Name_First_Charname + 44; Name_C140 : constant Name_Id := Name_First_Charname + 45; Name_C141 : constant Name_Id := Name_First_Charname + 46; Name_C142 : constant Name_Id := Name_First_Charname + 47; Name_C143 : constant Name_Id := Name_First_Charname + 48; Name_C144 : constant Name_Id := Name_First_Charname + 49; Name_C145 : constant Name_Id := Name_First_Charname + 50; Name_C146 : constant Name_Id := Name_First_Charname + 51; Name_C147 : constant Name_Id := Name_First_Charname + 52; Name_C148 : constant Name_Id := Name_First_Charname + 53; Name_C149 : constant Name_Id := Name_First_Charname + 54; Name_C150 :
# This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.

from __future__ import absolute_import, division, print_function

import binascii
import collections
import re
from contextlib import contextmanager

import pytest

import six

from cryptography.exceptions import UnsupportedAlgorithm

import cryptography_vectors


HashVector = collections.namedtuple("HashVector", ["message", "digest"])
KeyedHashVector = collections.namedtuple(
    "KeyedHashVector", ["message", "digest", "key"]
)


def select_backends(names, backend_list):
    if names is None:
        return backend_list
    split_names = [x.strip() for x in names.split(',')]
    selected_backends = []
    for backend in backend_list:
        if backend.name in split_names:
            selected_backends.append(backend)

    if len(selected_backends) > 0:
        return selected_backends
    else:
        raise ValueError(
            "No backend selected. Tried to select: {0}".format(split_names)
        )


def skip_if_empty(backend_list, required_interfaces):
    if not backend_list:
        pytest.skip(
            "No backends provided supply the interface: {0}".format(
                ", ".join(iface.__name__ for iface in required_interfaces)
            )
        )


def check_backend_support(item):
    supported = item.keywords.get("supported")
    if supported and "backend" in item.funcargs:
        if not supported.kwargs["only_if"](item.funcargs["backend"]):
            pytest.skip("{0} ({1})".format(
                supported.kwargs["skip_message"], item.funcargs["backend"]
            ))
    elif supported:
        raise ValueError("This mark is only available on methods that take a "
                         "backend")


@contextmanager
def raises_unsupported_algorithm(reason):
    with pytest.raises(UnsupportedAlgorithm) as exc_info:
        yield exc_info

    assert exc_info.value._reason is reason


def load_vectors_from_file(filename, loader, mode="r"):
    with cryptography_vectors.open_vector_file(filename, mode) as vector_file:
        return loader(vector_file)


def load_nist_vectors(vector_data):
    test_data = None
    data = []

    for line in vector_data:
        line = line.strip()

        # Blank lines, comments, and section headers are ignored
        if not line or line.startswith("#") or (line.startswith("[")
                                                and line.endswith("]")):
            continue

        if line.strip() == "FAIL":
            test_data["fail"] = True
            continue

        # Build our data using a simple Key = Value format
        name, value = [c.strip() for c in line.split("=")]

        # Some tests (PBKDF2) contain \0, which should be interpreted as a
        # null character rather than literal.
        value = value.replace("\\0", "\0")

        # COUNT is a special token that indicates a new block of data
        if name.upper() == "COUNT":
            test_data = {}
            data.append(test_data)
            continue
        # For all other tokens we simply want the name, value stored in
        # the dictionary
        else:
            test_data[name.lower()] = value.encode("ascii")

    return data


def load_cryptrec_vectors(vector_data):
    cryptrec_list = []

    for line in vector_data:
        line = line.strip()

        # Blank lines and comments are ignored
        if not line or line.startswith("#"):
            continue

        if line.startswith("K"):
            key = line.split(" : ")[1].replace(" ", "").encode("ascii")
        elif line.startswith("P"):
            pt = line.split(" : ")[1].replace(" ", "").encode("ascii")
        elif line.startswith("C"):
            ct = line.split(" : ")[1].replace(" ", "").encode("ascii")
            # after a C is found the K+P+C tuple is complete
            # there are many P+C pairs for each K
            cryptrec_list.append({
                "key": key,
                "plaintext": pt,
                "ciphertext": ct
            })
        else:
            raise ValueError("Invalid line in file '{}'".format(line))
    return cryptrec_list


def load_hash_vectors(vector_data):
    vectors = []
    key = None
    msg = None
    md = None

    for line in vector_data:
        line = line.strip()

        if not line or line.startswith("#") or line.startswith("["):
            continue

        if line.startswith("Len"):
            length = int(line.split(" = ")[1])
        elif line.startswith("Key"):
            # HMAC vectors contain a key attribute. Hash vectors do not.
            key = line.split(" = ")[1].encode("ascii")
        elif line.startswith("Msg"):
            # In the NIST vectors they have chosen to represent an empty
            # string as hex 00, which is of course not actually an empty
            # string. So we parse the provided length and catch this edge case.
            msg = line.split(" = ")[1].encode("ascii") if length > 0 else b""
        elif line.startswith("MD"):
            md = line.split(" = ")[1]
            # after MD is found the Msg+MD (+ potential key) tuple is complete
            if key is not None:
                vectors.append(KeyedHashVector(msg, md, key))
                key = None
                msg = None
                md = None
            else:
                vectors.append(HashVector(msg, md))
                msg = None
                md = None
        else:
            raise ValueError("Unknown line in hash vector")
    return vectors


def load_pkcs1_vectors(vector_data):
    """
    Loads data out of RSA PKCS #1 vector files.
    """
    private_key_vector = None
    public_key_vector = None
    attr = None
    key = None
    example_vector = None
    examples = []
    vectors = []
    for line in vector_data:
        if (
            line.startswith("# PSS Example") or
            line.startswith("# OAEP Example") or
            line.startswith("# PKCS#1 v1.5")
        ):
            if example_vector:
                for key, value in six.iteritems(example_vector):
                    hex_str = "".join(value).replace(" ", "").encode("ascii")
                    example_vector[key] = hex_str
                examples.append(example_vector)

            attr = None
            example_vector = collections.defaultdict(list)

        if line.startswith("# Message"):
            attr = "message"
            continue
        elif line.startswith("# Salt"):
            attr = "salt"
            continue
        elif line.startswith("# Seed"):
            attr = "seed"
            continue
        elif line.startswith("# Signature"):
            attr = "signature"
            continue
        elif line.startswith("# Encryption"):
            attr = "encryption"
            continue
        elif (
            example_vector and
            line.startswith("# =============================================")
        ):
            for key, value in six.iteritems(example_vector):
                hex_str = "".join(value).replace(" ", "").encode("ascii")
                example_vector[key] = hex_str
            examples.append(example_vector)
            example_vector = None
            attr = None
        elif example_vector and line.startswith("#"):
            continue
        else:
            if attr is not None and example_vector is not None:
                example_vector[attr].append(line.strip())
                continue

        if (
            line.startswith("# Example") or
            line.startswith("# =============================================")
        ):
            if key:
                assert private_key_vector
                assert public_key_vector

                for key, value in six.iteritems(public_key_vector):
                    hex_str = "".join(value).replace(" ", "")
                    public_key_vector[key] = int(hex_str, 16)

                for key, value in six.iteritems(private_key_vector):
                    hex_str = "".join(value).replace(" ", "")
                    private_key_vector[key] = int(hex_str, 16)

                private_key_vector["examples"] = examples
                examples = []

                assert (
                    private_key_vector['public_exponent'] ==
                    public_key_vector['public_exponent']
                )

                assert (
                    private_key_vector['modulus'] ==
                    public_key_vector['modulus']
                )

                vectors.append(
                    (private_key_vector, public_key_vector)
                )

            public_key_vector = collections.defaultdict(list)
            private_key_vector = collections.defaultdict(list)
            key = None
            attr = None

        if private_key_vector is None or public_key_vector is None:
            continue

        if line.startswith("# Private key"):
            key = private_key_vector
        elif line.startswith("# Public key"):
            key = public_key_vector
        elif line.startswith("# Modulus:"):
            attr = "modulus"
        elif line.startswith("# Public exponent:"):
            attr = "public_exponent"
        elif line.startswith("# Exponent:"):
            if key is public_key_vector:
                attr = "public_exponent"
            else:
                assert key is private_key_vector
                attr = "private_exponent"
        elif line.startswith("# Prime 1:"):
            attr = "p"
        elif line.startswith("# Prime 2:"):
            attr = "q"
        elif line.startswith("# Prime exponent 1:"):
            attr = "dmp1"
        elif line.startswith("# Prime exponent 2:"):
            attr = "dmq1"
        elif line.startswith("# Coefficient:"):
            attr = "iqmp"
        elif line.startswith("#"):
            attr = None
        else:
            if key is not None and attr is not None:
                key[attr].append(line.strip())
    return vectors


def load_rsa_nist_vectors(vector_data):
    test_data = None
    p = None
    salt_length = None
    data = []

    for line in vector_data:
        line = line.strip()

        # Blank lines and section headers are ignored
        if not line or line.startswith("["):
            continue

        if line.startswith("# Salt len:"):
            salt_length = int(line.split(":")[1].strip())
            continue
        elif line.startswith("#"):
            continue

        # Build our data using a simple Key = Value format
        name, value = [c.strip() for c in line.split("=")]

        if name == "n":
            n = int(value, 16)
        elif name == "e" and p is None:
            e = int(value, 16)
        elif name == "p":
            p = int(value, 16)
        elif name == "q":
            q = int(value, 16)
        elif name == "SHAAlg":
            if p is None:
                test_data = {
                    "modulus": n,
                    "public_exponent": e,
                    "salt_length": salt_length,
                    "algorithm": value,
                    "fail": False
                }
            else:
                test_data = {
                    "modulus": n,
                    "p": p,
                    "q": q,
                    "algorithm": value
                }
                if salt_length is not None:
                    test_data["salt_length"] = salt_length
            data.append(test_data)
        elif name == "e" and p is not None:
            test_data["public_exponent"] = int(value, 16)
        elif name == "d":
            test_data["private_exponent"] = int(value, 16)
        elif name == "Result":
            test_data["fail"] = value.startswith("F")
        # For all other tokens we simply want the name, value stored in
        # the dictionary
        else:
            test_data[name.lower()] = value.encode("ascii")

    return data


def load_fips_dsa_key_pair_vectors(vector_data):
    """
    Loads data out of the FIPS DSA KeyPair vector files.
    """
    vectors = []
    # When reading_key_data is set to True it tells the loader to continue
    # constructing dictionaries. We set reading_key_data to False during the
    # blocks of the vectors of N=224 because we don't support it.
    reading_key_data = True
    for line in vector_data:
        line = line.strip()

        if not line or line.startswith("#"):
            continue
        elif line.startswith("[mod = L=1024"):
            continue
        elif line.startswith("[mod = L=2048, N=224"):
            reading_key_data = False
            continue
        elif line.startswith("[mod = L=2048, N=256"):
            reading_key_data = True
            continue
        elif line.startswith("[mod = L=3072"):
            continue

        if not reading_key_data:
            continue

        elif reading_key_data:
            if line.startswith("P"):
                vectors.append({'p': int(line.split("=")[1], 16)})
            elif line.startswith("Q"):
                vectors[-1]['q'] = int(line.split("=")[1], 16)
            elif line.startswith("G"):
                vectors[-1]['g'] = int(line.split("=")[1], 16)
            elif line.startswith("X") and 'x' not in vectors[-1]:
                vectors[-1]['x'] = int(line.split("=")[1], 16)
            elif line.startswith("X") and 'x' in vectors[-1]:
                vectors.append({'p': vectors[-1]['p'],
                                'q': vectors[-1]['q'],
                                'g': vectors[-1]['g'],
                                'x': int(line.split("=")[1], 16)
                                })
            elif line.startswith("Y"):
                vectors[-1]['y'] = int(line.split("=")[1], 16)

    return vectors


def load_fips_dsa_sig_vectors(vector_data):
    """
    Loads data out of the FIPS DSA SigVer vector files.
    """
    vectors = []
    sha_regex = re.compile(
        r"\[mod = L=...., N=..., SHA-(?P<sha>1|224|256|384|512)\]"
    )
    # When reading_key_data is set to True it tells the loader to continue
    # constructing dictionaries. We set reading_key_data to False during the
    # blocks of the vectors of N=224 because we don't support it.
    reading_key_data = True

    for line in vector_data:
        line = line.strip()

        if not line or line.startswith("#"):
            continue

        sha_match = sha_regex.match(line)
        if sha_match:
            digest_algorithm = "SHA-{0}".format(sha_match.group("sha"))

        if line.startswith("[mod = L=2048, N=224"):
            reading_key_data = False
            continue
        elif line.startswith("[mod = L=2048, N=256"):
            reading_key_data = True
            continue

        if not reading_key_data or line.startswith("[mod"):
            continue

        name, value = [c.strip() for c in line.split("=")]

        if name == "P":
            vectors.append({'p': int(value, 16),
                            'digest_algorithm': digest_algorithm})
        elif name == "Q":
            vectors[-1]['q'] = int(value, 16)
        elif name == "G":
            vectors[-1]['g'] = int(value, 16)
        elif name == "Msg" and 'msg' not in vectors[-1]:
            hexmsg = value.strip().encode("ascii")
            vectors[-1]['msg'] = binascii.unhexlify(hexmsg)
        elif name == "Msg" and 'msg' in vectors[-1]:
            hexmsg = value.strip().encode("ascii")
            vectors.append({'p': vectors[-1]['p'],
                            'q': vectors[-1]['q'],
                            'g': vectors[-1]['g'],
                            'digest_algorithm':
                            vectors[-1]['digest_algorithm'],
                            'msg': binascii.unhexlify(hexmsg)})
        elif name == "X":
            vectors[-1]['x'] = int(value, 16)
        elif name == "Y":
            vectors[-1]['y'] = int(value, 16)
        elif name == "R":
            vectors[-1]['r'] = int(value, 16)
        elif name == "S":
            vectors[-1]['s'] = int(value, 16)
        elif name == "Result":
            vectors[-1]['result'] = value.split("(")[0].strip()

    return vectors


# http://tools.ietf.org/html/rfc4492#appendix-A
_ECDSA_CURVE_NAMES = {
    "P-192": "secp192r1",
    "P-224": "secp224r1",
    "P-256": "secp256r1",
    "P-384": "secp384r1",
    "P-521": "secp521r1",

    "K-163": "sect163k1",
    "K-233": "sect233k1",
    "K-283": "sect283k1",
    "K-409": "sect409k1",
    "K-571": "sect571k1",

    "B-163": "sect163r2",
    "B-233": "sect233r1",
    "B-283": "sect283r1",
    "B-409": "sect409r1",
    "B-571": "sect571r1",
}


def load_fips_ecdsa_key_pair_vectors(vector_data):
    """
    Loads data out of the FIPS ECDSA KeyPair vector files.
    """
    vectors = []
    key_data = None
    for line in vector_data:
        line = line.strip()

        if not line or line.startswith("#"):
            continue

        if line[1:-1] in _ECDSA_CURVE_NAMES:
            curve_name = _ECDSA_CURVE_NAMES[line[1:-1]]

        elif line.startswith("d = "):
            if key_data is not None:
                vectors.append(key_data)

            key_data = {
                "curve": curve_name,
                "d": int(line.split("=")[1], 16)
            }

        elif key_data is not None:
            if line.startswith("Qx = "):
                key_data["x"] = int(line.split("=")[1], 16)
            elif line.startswith("Qy = "):
                key_data["y"] = int(line.split("=")[1], 16)

    if key_data is not None:
        vectors.append(key_data)

    return vectors


def load_fips_ecdsa_signing_vectors(vector_data):
    """
    Loads data out of the FIPS ECDSA SigGen vector files.
    """
    vectors = []

    curve_rx = re.compile(
        r"\[(?P<curve>[PKB]-[0-9]{3}),SHA-(?P<sha>1|224|256|384|512)\]"
    )

    data = None
    for line in vector_data:
        line = line.strip()

        if not line or line.startswith("#"):
            continue

        curve_match = curve_rx.match(line)
        if curve_match:
            curve_name = _ECDSA_CURVE_NAMES[curve_match.group("curve")]
            digest_name = "SHA-{0}".format(curve_match.group("sha"))

        elif line.startswith("Msg = "):
            if data is not None:
                vectors.append(data)

            hexmsg = line.split("=")[1].strip().encode("ascii")

            data = {
                "curve": curve_name,
                "digest_algorithm": digest_name,
                "message": binascii.unhexlify(hexmsg)
            }

        elif data is not None:
            if line.startswith("Qx = "):
                data["x"] = int(line.split("=")[1], 16)
            elif line.startswith("Qy = "):
                data["y"] = int(line.split("=")[1], 16)
            elif line.startswith("R = "):
                data["r"] = int(line.split("=")[1], 16)
            elif line.startswith("S = "):
                data["s"] = int(line.split("=")[1], 16)
            elif line.startswith("d = "):
                data["d"] = int(line.split("=")[1], 16)
            elif line.startswith("Result = "):
                data["fail"] = line.split("=")[1].strip()[0] == "F"

    if data is not None:
        vectors.append(data)
    return vectors


def load_kasvs_dh_vectors(vector_data):
    """
    Loads data out of the KASVS key exchange vector data
    """

    result_rx = re.compile(r"([FP]) \(([0-9]+) -")

    vectors = []
    data = {
        "fail_z": False,
        "fail_agree": False
    }

    for line in vector_data:
        line = line.strip()

        if not line or line.startswith("#"):
            continue

        if line.startswith("P = "):
            data["p"] = int(line.split("=")[1], 16)
        elif line.startswith("Q = "):
            data["q"] = int(line.split("=")[1], 16)
        elif line.startswith("G = "):
            data["g"] = int(line.split("=")[1], 16)
        elif line.startswith("Z = "):
            z_hex = line.split("=")[1].strip().encode("ascii")
            data["z"] = binascii.unhexlify(z_hex)
        elif line.startswith("XstatCAVS = "):
            data["x1"] = int(line.split("=")[1], 16)
        elif line.startswith("YstatCAVS = "):
            data["y1"] = int(line.split("=")[1], 16)
        elif line.startswith("XstatIUT = "):
            data["x2"] = int(line.split("=")[1], 16)
        elif line.startswith("YstatIUT = "):
            data["y2"] = int(line.split("=")[1], 16)
        elif line.startswith("Result = "):
            result_str = line.split("=")[1].strip()
            match = result_rx.match(result_str)

            if match.group(1) == "F":
                if int(match.group(2)) in (5, 10):
                    data["fail_z"] = True
                else:
                    data["fail_agree"] = True

            vectors.append(data)

            data = {
                "p": data["p"],
                "q": data["q"],
                "g": data["g"],
                "fail_z": False,
                "fail_agree": False
            }

    return vectors