Add length check at CGitHash(CString $str)
[TortoiseGit.git] / src / Git / GitHash.h
blobc494879e208df38c32010f369311555bf97f81bb
1 #pragma once
2 #if defined(_MFC_VER)
3 #include "afx.h"
4 #endif
5 #define GIT_HASH_SIZE 20
7 class CGitHash
9 public:
10 unsigned char m_hash[GIT_HASH_SIZE];
12 CGitHash()
14 memset(m_hash,0, GIT_HASH_SIZE);
16 CGitHash(char *p)
18 memcpy(m_hash,p,GIT_HASH_SIZE);
20 CGitHash & operator = (CString &str)
22 CGitHash hash(str);
23 *this = hash;
24 return *this;
26 CGitHash(CString &str)
28 if(str.GetLength()<GIT_HASH_SIZE)
30 #ifdef ASSERT
31 ASSERT(FALSE);
32 #endif
33 return;
36 for(int i=0;i<GIT_HASH_SIZE;i++)
38 unsigned char a;
39 a=0;
40 for(int j=2*i;j<=2*i+1;j++)
42 a =a<<4;
44 TCHAR ch = str[j];
45 if(ch >= _T('0') && ch <= _T('9'))
46 a |= (ch - _T('0'))&0xF;
47 else if(ch >=_T('A') && ch <= _T('F'))
48 a |= ((ch - _T('A'))&0xF) + 10 ;
49 else if(ch >=_T('a') && ch <= _T('f'))
50 a |= ((ch - _T('a'))&0xF) + 10;
53 m_hash[i]=a;
56 void Empty()
58 memset(m_hash,0, GIT_HASH_SIZE);
60 bool IsEmpty()
62 for(int i=0;i<GIT_HASH_SIZE;i++)
64 if(m_hash[i] != 0)
65 return false;
67 return true;
70 CString ToString()
72 CString str;
73 CString a;
74 for(int i=0;i<GIT_HASH_SIZE;i++)
76 a.Format(_T("%02x"),m_hash[i]);
77 str+=a;
79 return str;
81 operator CString ()
83 return ToString();
86 bool operator == (const CGitHash &hash)
88 return memcmp(m_hash,hash.m_hash,GIT_HASH_SIZE) == 0;
92 friend bool operator<(const CGitHash& left, const CGitHash& right)
94 return memcmp(left.m_hash,right.m_hash,GIT_HASH_SIZE) < 0;
97 friend bool operator>(const CGitHash& left, const CGitHash& right)
99 return memcmp(left.m_hash, right.m_hash, GIT_HASH_SIZE) > 0;
102 friend bool operator != (const CGitHash& left, const CGitHash& right)
104 return memcmp(left.m_hash, right.m_hash, GIT_HASH_SIZE) != 0;
106 #if defined(_MFC_VER)
107 friend CArchive& AFXAPI operator<<(CArchive& ar, CGitHash& hash)
109 for(int i=0;i<GIT_HASH_SIZE;i++)
110 ar<<hash.m_hash[i];
111 return ar;
113 friend CArchive& AFXAPI operator>>(CArchive& ar, CGitHash& hash)
115 for(int i=0;i<GIT_HASH_SIZE;i++)
116 ar>>hash.m_hash[i];
117 return ar;
119 #endif