Skip to content

Instantly share code, notes, and snippets.

@MtShadow
Created May 13, 2016 19:05
Show Gist options
  • Save MtShadow/d13fdd8eb8750a0410cf3aa128cbc1be to your computer and use it in GitHub Desktop.
Save MtShadow/d13fdd8eb8750a0410cf3aa128cbc1be to your computer and use it in GitHub Desktop.
MySQL hamming_distance
#include <string.h>
#include <mysql.h>
my_bool hamming_distance_init(initid, args, message)
UDF_INIT *initid;
UDF_ARGS *args;
char *message;
{
if (args->arg_count != 2) {
strcpy( message, "Wrong number of arguments to HAMMING_DISTANCE; accepts exactly two arguments." );
return 1;
}
if ((args->arg_type[0] != STRING_RESULT) || (args->arg_type[1] != STRING_RESULT)) {
strcpy( message, "One or both arguments to HAMMING_DISTANCE is not an string." );
return 1;
}
return 0;
}
void hamming_distance_deinit(initid)
UDF_INIT *initid;
{
return;
}
long long hamming_distance(initid, args, is_null, error)
UDF_INIT *initid;
UDF_ARGS *args;
char *is_null;
char *error;
{
if ((args->args[0] == NULL) || (args->args[1] == NULL)) {
*error = 1;
return 0;
}
if (args->lengths[0] != args->lengths[1]) {
*error = 1;
return 0;
}
if ((args->lengths[0] % 8) != 0) {
*error = 1;
return 0;
}
long long count = 0ll;
int i, j;
long long *v1 = (long long *)args->args[0];
long long *v2 = (long long *)args->args[1];
for(i = 0; i < (int)(args->lengths[0] / 8); i++) {
count += __builtin_popcountll(v1[i] ^ v2[i]);
}
return count;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment