Exemplo n.º 1
0
        public Hashids(string salt = "", int minHashLength = MIN_HASH_LENGTH, string alphabet = DEFAULT_ALPHABET)
        {
            if (string.IsNullOrWhiteSpace(alphabet))
            {
                throw new ArgumentNullException("alphabet");
            }

            if (alphabet.Contains(' '))
            {
                throw new ArgumentException("alphabet cannot contain spaces", "alphabet");
            }

            Alphabet = new String(alphabet.Distinct().ToArray());

            Salt          = salt;
            MinHashLength = minHashLength;

            // separators should be in the alphabet
            Separators = DEFAULT_SEPARATORS;
            Separators = new String(Separators.Where(x => Alphabet.Contains(x)).ToArray());

            if (string.IsNullOrWhiteSpace(Separators))
            {
                throw new ArgumentException("alphabet does not contain separators", "separators");
            }

            Separators = ConsistentShuffle(input: Separators, salt: Salt);

            // remove separator characters from the alphabet
            Alphabet = new String(Alphabet.Where(x => !Separators.Contains(x)).ToArray());

            if (string.IsNullOrWhiteSpace(Alphabet) || Alphabet.Length < MIN_ALPHABET_LENGTH)
            {
                throw new ArgumentException("alphabet must contain atleast " + MIN_ALPHABET_LENGTH + " unique, non-separator characters.", "alphabet");
            }

            double sepDivisor = 3.5;

            if ((Separators.Length == 0) || (((double)Alphabet.Length / (double)Separators.Length) > sepDivisor))
            {
                int sepsLength = (int)Math.Ceiling(Alphabet.Length / sepDivisor);

                if (sepsLength == 1)
                {
                    sepsLength++;
                }

                if (sepsLength > Separators.Length)
                {
                    int diff = sepsLength - Separators.Length;
                    Separators += Alphabet.Substring(0, diff);
                    Alphabet    = Alphabet.Substring(diff);
                }
                else
                {
                    Separators = Separators.Substring(0, sepsLength);
                }
            }

            double guardDivisor = 12.0;

            Alphabet = ConsistentShuffle(input: Alphabet, salt: Salt);
            int guardCount = (int)Math.Ceiling(Alphabet.Length / guardDivisor);

            if (Alphabet.Length < 3)
            {
                Guards     = Separators.Substring(0, guardCount);
                Separators = Separators.Substring(guardCount);
            }
            else
            {
                Guards   = Alphabet.Substring(0, guardCount);
                Alphabet = Alphabet.Substring(guardCount);
            }
        }