Skip to content

Instantly share code, notes, and snippets.

@tallpeak
Created October 28, 2022 12:34
Show Gist options
  • Save tallpeak/edc76ab9d59a8393e16ab337f13ab052 to your computer and use it in GitHub Desktop.
Save tallpeak/edc76ab9d59a8393e16ab337f13ab052 to your computer and use it in GitHub Desktop.
#include "postgres.h"
#include <string.h>
#include "fmgr.h"
#include "utils/geo_decls.h"
PG_MODULE_MAGIC;
/* by value */
PG_FUNCTION_INFO_V1(upc_checkdigit);
Datum
upc_checkdigit(PG_FUNCTION_ARGS)
{
text *upc = PG_GETARG_TEXT_PP(0);
int sum = 0;
int mult = 3;
char *pstart = VARDATA_ANY(upc);
char *p = pstart + VARSIZE_ANY_EXHDR(upc);
while (--p >= pstart) {
unsigned int digit = *p - '0';
if (digit < 10) {
sum += digit * mult;
mult ^= 2;
}
}
sum = (500 - sum) % 10;
// sum = ( 10 - ( sum % 10 ) ) % 10;
PG_RETURN_INT32(sum);
}
// so far untested
PG_FUNCTION_INFO_V1(upc_checksum);
Datum
upc_checksum(PG_FUNCTION_ARGS)
{
text *upc = PG_GETARG_TEXT_PP(0);
int sum = 0;
int mult = 1;
char *pstart = VARDATA_ANY(upc);
char *p = pstart + VARSIZE_ANY_EXHDR(upc);
while (--p >= pstart) {
unsigned int digit = *p - '0';
if (digit < 10) {
sum += digit * mult;
mult ^= 2;
}
}
sum %= 10;
PG_RETURN_INT32(sum);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment