moved back to old acc
[vox.git] / src / core / baselib_hashlib.cpp
blobd2477ce0afc3c3caa37cd81317ea677adfade650
2 #include "baselib.hpp"
3 #include "hash.hpp"
5 template<typename Type> struct VXHashProxy
7 Type* instance;
9 VXHashProxy()
11 this->instance = new Type;
14 ~VXHashProxy()
16 delete this->instance;
21 template<typename Type> VXInteger hashclass_releasehook(VXUserPointer p, VXInteger)
23 VXHashProxy<Type>* self = (VXHashProxy<Type>*)p;
24 delete self;
25 return 1;
28 template<typename Type> VXInteger hashclass_constructor(VXState* v)
30 VXHashProxy<Type>* self;
31 self = new VXHashProxy<Type>;
32 v->SetInstanceUp(1, (VXUserPointer*)&self);
33 v->SetReleaseHook(1, hashclass_releasehook<Type>);
34 return 1;
37 VXInteger hashclass_update(VXState* v)
39 VXHashProxy<Hash::Object>* self;
40 std::string value;
41 v->GetInstanceUp(1, (VXUserPointer*)&self, 0);
42 v->GetString(2, &value);
43 self->instance->update(value);
44 return VX_OK;
47 VXInteger hashclass_update_char(VXState* v)
49 VXHashProxy<Hash::Object>* self;
50 VXInteger value;
51 v->GetInstanceUp(1, (VXUserPointer*)&self, 0);
52 v->GetInteger(2, &value);
53 self->instance->update(value);
54 return VX_OK;
57 VXInteger hashclass_update_file(VXState* v)
59 VXHashProxy<Hash::Object>* self;
60 std::string path;
61 v->GetInstanceUp(1, (VXUserPointer*)&self, 0);
62 v->GetString(2, &path);
63 self->instance->updateFromFile(path);
64 return VX_OK;
67 VXInteger hashclass_finalize(VXState* v)
69 VXHashProxy<Hash::Object>* self;
70 v->GetInstanceUp(1, (VXUserPointer*)&self, 0);
71 self->instance->finalize();
72 return VX_OK;
75 VXInteger hashclass_hexdigest(VXState* v)
77 VXHashProxy<Hash::Object>* self;
78 std::string hd;
79 v->GetInstanceUp(1, (VXUserPointer*)&self, 0);
80 try
82 hd = self->instance->hexDigest();
83 v->Push(v->NewString(hd.c_str(), hd.length()));
84 return 1;
86 catch(Hash::Error& err)
88 return v->ThrowError(err.what());
90 return VX_ERROR;
93 template<typename Type> VXRegFunction* hashfuncs()
95 static VXRegFunction funcs[] =
97 {"constructor", hashclass_constructor<Type>, 0, "x"},
98 {"update", hashclass_update, 2, ".s"},
99 {"update_char", hashclass_update_char, 2, ".n"},
100 {"update_file", hashclass_update_file, 2, ".s"},
101 {"finalize", hashclass_finalize, 0, "x"},
102 {"hexdigest", hashclass_hexdigest, 0, "x"},
103 {0, 0, 0, 0},
105 return funcs;
108 VXInteger voxstd_register_hashlib(VXState* v)
110 VXTableObj* tb;
111 tb = v->NewTable();
112 tb->NewSlot(v->NewString("SHA1"), v->RegClass(hashfuncs<Hash::SHA1>()));
113 tb->NewSlot(v->NewString("MD5"), v->RegClass(hashfuncs<Hash::MD5>()));
114 v->GetRootTable()->NewSlot(v->NewString("hashlib"), tb);
115 return VX_OK;