gnu: linux-libre: Update to 5.1.4.
[guix.git] / nix / libutil / hash.hh
blob6b5e47cd8a29c1ad8fb5c5939aa1392b0b09372b
1 #pragma once
3 #include "types.hh"
4 #include "serialise.hh"
7 namespace nix {
10 typedef enum { htUnknown, htMD5, htSHA1, htSHA256, htSHA512 } HashType;
13 const int md5HashSize = 16;
14 const int sha1HashSize = 20;
15 const int sha256HashSize = 32;
16 const int sha512HashSize = 64;
18 extern const string base32Chars;
21 struct Hash
23 static const unsigned int maxHashSize = 64;
24 unsigned int hashSize;
25 unsigned char hash[maxHashSize];
27 HashType type;
29 /* Create an unusable hash object. */
30 Hash();
32 /* Create a zero-filled hash object. */
33 Hash(HashType type);
35 /* Check whether two hash are equal. */
36 bool operator == (const Hash & h2) const;
38 /* Check whether two hash are not equal. */
39 bool operator != (const Hash & h2) const;
41 /* For sorting. */
42 bool operator < (const Hash & h) const;
46 /* Convert a hash to a hexadecimal representation. */
47 string printHash(const Hash & hash);
49 /* Parse a hexadecimal representation of a hash code. */
50 Hash parseHash(HashType ht, const string & s);
52 /* Returns the length of a base-32 hash representation. */
53 unsigned int hashLength32(const Hash & hash);
55 /* Convert a hash to a base-32 representation. */
56 string printHash32(const Hash & hash);
58 /* Print a hash in base-16 if it's MD5, or base-32 otherwise. */
59 string printHash16or32(const Hash & hash);
61 /* Parse a base-32 representation of a hash code. */
62 Hash parseHash32(HashType ht, const string & s);
64 /* Parse a base-16 or base-32 representation of a hash code. */
65 Hash parseHash16or32(HashType ht, const string & s);
67 /* Verify that the given string is a valid hash code. */
68 bool isHash(const string & s);
70 /* Compute the hash of the given string. */
71 Hash hashString(HashType ht, const string & s);
73 /* Compute the hash of the given file. */
74 Hash hashFile(HashType ht, const Path & path);
76 /* Compute the hash of the given path. The hash is defined as
77 (essentially) hashString(ht, dumpPath(path)). */
78 struct PathFilter;
79 extern PathFilter defaultPathFilter;
80 typedef std::pair<Hash, unsigned long long> HashResult;
81 HashResult hashPath(HashType ht, const Path & path,
82 PathFilter & filter = defaultPathFilter);
84 /* Compress a hash to the specified number of bytes by cyclically
85 XORing bytes together. */
86 Hash compressHash(const Hash & hash, unsigned int newSize);
88 /* Parse a string representing a hash type. */
89 HashType parseHashType(const string & s);
91 /* And the reverse. */
92 string printHashType(HashType ht);
95 struct Ctx;
97 class HashSink : public BufferedSink
99 private:
100 HashType ht;
101 Ctx * ctx;
102 unsigned long long bytes;
104 public:
105 HashSink(HashType ht);
106 HashSink(const HashSink & h);
107 ~HashSink();
108 void write(const unsigned char * data, size_t len);
109 HashResult finish();
110 HashResult currentHash();