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
"
"
"
"
"
"
"
"
"
"
"
"
" |
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
" |
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
"
]
}
],
"source": [
"correct = 0\n",
"for i in range(10000):\n",
" with open(f\"X_test/{i}.json\", \"r\") as f:\n",
" input = json.load(f)\n",
" out, _ = inference(input, circuit)\n",
" correct += 1 if out[0] == y_test[i] else 0\n",
" print(f\"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "keras2circom",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.13"
}
},
"nbformat": 4,
"nbformat_minor": 2
} |
const chai = require('chai');
const fs = require('fs');
const wasm_tester = require('circom_tester').wasm;
const F1Field = require('ffjavascript').F1Field;
const Scalar = require('ffjavascript').Scalar;
exports.p = Scalar.fromString('21888242871839275222246405745257275088548364400416034343698204186575808495617');
const Fr = new F1Field(exports.p);
const assert = chai.assert;
const exec = require('await-exec');
const input = require('../test/X_test/0.json');
describe('keras2circom test', function () {
this.timeout(100000000);
describe('softmax output', async () => {
it('softmax output test', async () => {
await exec('python main.py models/model.h5 && python output/circuit.py output/circuit.json test/X_test/0.json');
const model = JSON.parse(fs.readFileSync('./output/circuit.json'));
const output = JSON.parse(fs.readFileSync('./output/output.json'));
const INPUT = {...model, ...input, ...output};
const circuit = await wasm_tester('./output/circuit.circom');
const witness = await circuit.calculateWitness(INPUT, true);
assert(Fr.eq(Fr.e(witness[0]),Fr.e(1)));
assert(Fr.eq(Fr.e(witness[1]),Fr.e(7)));
});
});
describe('raw output', async () => {
it('raw output test', async () => {
await exec('python main.py models/model.h5 --raw && python output/circuit.py output/circuit.json test/X_test/0.json');
const model = JSON.parse(fs.readFileSync('./output/circuit.json'));
const output = JSON.parse(fs.readFileSync('./output/output.json'));
const INPUT = {...model, ...input, ...output};
const circuit = await wasm_tester('./output/circuit.circom');
const witness = await circuit.calculateWitness(INPUT, true);
assert(Fr.eq(Fr.e(witness[0]),Fr.e(1)));
});
});
}); |
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"from tensorflow.keras.datasets import mnist\n",
"import json\n",
"import numpy as np"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"# load MNIST dataset\n",
"_, (X_test, y_test) = mnist.load_data()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"#normalizing\n",
"X_test = X_test.astype('float32')\n",
"X_test /= 255.0"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"for i in range(len(X_test)):\n",
" X = [str(int(x * float(10**18))) for x in X_test[i].flatten().tolist()]\n",
" X = np.array(X).reshape(28, 28, 1).tolist()\n",
" with open(f'X_test/{i}.json', 'w') as f:\n",
" json.dump({\"in\": X}, f)"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"with open('y_test.json', 'w') as f:\n",
" json.dump(y_test.tolist(), f)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "keras2circom",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.13"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
|
/* cma.h
*
* The MIT License (MIT)
*
* COPYRIGHT (C) 2017 Institute of Electronics and Computer Science (EDI), Latvia.
* AUTHOR: Rihards Novickis ([email protected])
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef VTA_DE10_NANO_KERNEL_MODULE_CMA_H_
#define VTA_DE10_NANO_KERNEL_MODULE_CMA_H_
/* Should be defined in settings.mk file */
#ifndef CMA_IOCTL_MAGIC
#define CMA_IOCTL_MAGIC 0xf2
#endif
#define CMA_ALLOC_CACHED _IOC(_IOC_WRITE | _IOC_READ, CMA_IOCTL_MAGIC, 1, 4)
#define CMA_ALLOC_NONCACHED _IOC(_IOC_WRITE | _IOC_READ, CMA_IOCTL_MAGIC, 2, 4)
#define CMA_FREE _IOC(_IOC_WRITE, CMA_IOCTL_MAGIC, 3, 4)
#define CMA_GET_PHY_ADDR _IOC(_IOC_WRITE | _IOC_READ, CMA_IOCTL_MAGIC, 4, 4)
#define CMA_GET_SIZE _IOC(_IOC_WRITE | _IOC_READ, CMA_IOCTL_MAGIC, 5, 4)
#define CMA_IOCTL_MAXNR 5
#endif // VTA_DE10_NANO_KERNEL_MODULE_CMA_H_
|
/*
* The MIT License (MIT)
*
* COPYRIGHT (C) 2017 Institute of Electronics and Computer Science (EDI), Latvia.
* AUTHOR: Rihards Novickis ([email protected])
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
/*!
* Copyright (c) 2018 by Contributors
* \file cma_api.cc
* \brief Application layer implementation for contigous memory allocation.
*/
/* Private functions */
void* cma_alloc(size_t size, unsigned ioctl_cmd);
/* Global file descriptor */
int cma_fd = 0;
int cma_init(void) {
__DEBUG("Opening \"/dev/" DRIVER_NODE_NAME "\" file\n");
cma_fd = open("/dev/" DRIVER_NODE_NAME, O_RDWR);
if (cma_fd == -1) {
__DEBUG("Failed to initialize api - \"%s\"\n", strerror(errno));
return -1;
}
return 0;
}
int cma_release(void) {
__DEBUG("Closing \"/dev/" DRIVER_NODE_NAME "\" file\n");
if (close(cma_fd) == -1) {
__DEBUG("Failed to finilize api - \"%s\"\n", strerror(errno));
return -1;
}
return 0;
}
void* cma_alloc_cach |
ed(size_t size) { return cma_alloc(size, CMA_ALLOC_CACHED); }
void* cma_alloc_noncached(size_t size) { return cma_alloc(size, CMA_ALLOC_NONCACHED); }
int cma_free(void* mem) {
__DEBUG("Releasing contigous memory from 0x%x\n", (unsigned)mem);
unsigned data, v_addr;
/* save user space pointer value */
data = (unsigned)mem;
v_addr = (unsigned)mem;
if (ioctl(cma_fd, CMA_GET_SIZE, &data) == -1) {
__DEBUG("cma_free - ioctl command unsuccsessful - 0\n");
return -1;
}
/* data now contains size */
/* unmap memory */
munmap(mem, data);
/* free cma entry */
if (ioctl(cma_fd, CMA_FREE, &v_addr) == -1) {
__DEBUG("cma_free - ioctl command unsuccsessful - 1\n");
return -1;
}
return 0;
}
unsigned cma_get_phy_addr(void* mem) {
unsigned data;
__DEBUG("Getting physical address from 0x%x\n", (unsigned)mem);
/* save user space pointer value */
data = (unsigned)mem;
/* get physical address */
if (ioctl(cma_fd, CMA_GET_PHY_ADDR, &data) == -1) {
__DEBUG("cma_free - ioctl command unsuccsessful\n");
return 0;
}
/* data now contains physical address */
return data;
}
void* cma_alloc(size_t size, unsigned ioctl_cmd) {
unsigned data;
void* mem;
__DEBUG("Allocating 0x%x bytes of contigous memory\n", size);
/* Page align size */
size = ROUND_UP(size, getpagesize());
/* ioctl cmd to allocate contigous memory */
data = (unsigned)size;
if (ioctl(cma_fd, ioctl_cmd, &data) == -1) {
__DEBUG("cma_alloc - ioctl command unsuccsessful\n");
return NULL;
}
/* at this point phy_addr is written to data */
/* mmap memory */
mem = mmap(NULL, size, PROT_WRITE | PROT_READ, MAP_SHARED, cma_fd, data);
if (mem == MAP_FAILED) {
__DEBUG("cma_alloc - mmap unsuccsessful\n");
return NULL;
}
return mem;
} |
/*
* Copyright (c) 2009-2015 by llvm/compiler-rt contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
* \file builtin_fp16.h
* \brief Functions for conversion between fp32 and fp16, adopted from compiler-rt.
*/
static inline uint32_t __clz(uint32_t x) {
int n = 32;
uint32_t y;
y = x >> 16;
if (y) {
n = n - 16;
x = y;
}
y = x >> 8;
if (y) {
n = n - 8;
x = y;
}
y = x >> 4;
if (y) {
n = n - 4;
x = y;
}
y = x >> 2;
if (y) {
n = n - 2;
x = y;
}
y = x >> 1;
if (y) return n - 2;
return n - x;
}
template <typename SRC_T, typename SRC_REP_T, int SRC_SIG_BITS, typename DST_T, typename DST_REP_T,
int DST_SIG_BITS>
static inline DST_T __truncXfYf2__(SRC_T a) {
const int srcBits = sizeof(SRC_T) * 8;
const int srcExpBits = srcBits - SRC_SIG_BITS - 1;
const int srcInfExp = (1 << srcExpBits) - 1;
const int srcExpBias = srcInfExp >> 1;
const SRC_REP_T srcMinNormal = SRC_REP_T(1) << SRC_SIG_BITS;
const SR |
C_REP_T srcSignificandMask = srcMinNormal - 1;
const SRC_REP_T srcInfinity = (SRC_REP_T)srcInfExp << SRC_SIG_BITS;
const SRC_REP_T srcSignMask = SRC_REP_T(1) << (SRC_SIG_BITS + srcExpBits);
const SRC_REP_T srcAbsMask = srcSignMask - 1;
const SRC_REP_T roundMask = (SRC_REP_T(1) << (SRC_SIG_BITS - DST_SIG_BITS)) - 1;
const SRC_REP_T halfway = SRC_REP_T(1) << (SRC_SIG_BITS - DST_SIG_BITS - 1);
const SRC_REP_T srcQNaN = SRC_REP_T(1) << (SRC_SIG_BITS - 1);
const SRC_REP_T srcNaNCode = srcQNaN - 1;
const int dstBits = sizeof(DST_T) * 8;
const int dstExpBits = dstBits - DST_SIG_BITS - 1;
const int dstInfExp = (1 << dstExpBits) - 1;
const int dstExpBias = dstInfExp >> 1;
const int underflowExponent = srcExpBias + 1 - dstExpBias;
const int overflowExponent = srcExpBias + dstInfExp - dstExpBias;
const SRC_REP_T underflow = (SRC_REP_T)underflowExponent << SRC_SIG_BITS;
const SRC_REP_T overflow = (SRC_REP_T)overflowExponent << SRC_SIG_BITS;
const DST_REP_T dstQNaN = DST_REP_T(1) << (DST_SIG_BITS - 1);
const DST_REP_T dstNaNCode = dstQNaN - 1;
union SrcExchangeType {
SRC_T f;
SRC_REP_T i;
};
SrcExchangeType src_rep;
src_rep.f = a;
const SRC_REP_T aRep = src_rep.i;
const SRC_REP_T aAbs = aRep & srcAbsMask;
const SRC_REP_T sign = aRep & srcSignMask;
DST_REP_T absResult;
if (aAbs - underflow < aAbs - overflow) {
absResult = aAbs >> (SRC_SIG_BITS - DST_SIG_BITS);
absResult -= (DST_REP_T)(srcExpBias - dstExpBias) << DST_SIG_BITS;
const SRC_REP_T roundBits = aAbs & roundMask;
if (roundBits > halfway) absResult++;
else if (roundBits == halfway)
absResult += absResult & 1;
} else if (aAbs > srcInfinity) {
absResult = (DST_REP_T)dstInfExp << DST_SIG_BITS;
absResult |= dstQNaN;
absResult |= ((aAbs & srcNaNCode) >> (SRC_SIG_BITS - DST_SIG_BITS)) & dstNaNCode;
} else if (aAbs >= overflow) {
absResult = (DST_REP_T)dstInfExp << DST_SIG_BITS;
} else {
const int a |
Exp = aAbs >> SRC_SIG_BITS;
const int shift = srcExpBias - dstExpBias - aExp + 1;
const SRC_REP_T significand = (aRep & srcSignificandMask) | srcMinNormal;
if (shift > SRC_SIG_BITS) {
absResult = 0;
} else {
const bool sticky = significand << (srcBits - shift);
SRC_REP_T denormalizedSignificand = significand >> shift | sticky;
absResult = denormalizedSignificand >> (SRC_SIG_BITS - DST_SIG_BITS);
const SRC_REP_T roundBits = denormalizedSignificand & roundMask;
if (roundBits > halfway) absResult++;
else if (roundBits == halfway)
absResult += absResult & 1;
}
}
const DST_REP_T result = absResult | sign >> (srcBits - dstBits);
union DstExchangeType {
DST_T f;
DST_REP_T i;
};
DstExchangeType dst_rep;
dst_rep.i = result;
return dst_rep.f;
}
template <typename SRC_T, typename SRC_REP_T, int SRC_SIG_BITS, typename DST_T, typename DST_REP_T,
int DST_SIG_BITS>
static inline DST_T __extendXfYf2__(SRC_T a) {
const int srcBits = sizeof(SRC_T) * 8;
const int srcExpBits = srcBits - SRC_SIG_BITS - 1;
const int srcInfExp = (1 << srcExpBits) - 1;
const int srcExpBias = srcInfExp >> 1;
const SRC_REP_T srcMinNormal = SRC_REP_T(1) << SRC_SIG_BITS;
const SRC_REP_T srcInfinity = (SRC_REP_T)srcInfExp << SRC_SIG_BITS;
const SRC_REP_T srcSignMask = SRC_REP_T(1) << (SRC_SIG_BITS + srcExpBits);
const SRC_REP_T srcAbsMask = srcSignMask - 1;
const SRC_REP_T srcQNaN = SRC_REP_T(1) << (SRC_SIG_BITS - 1);
const SRC_REP_T srcNaNCode = srcQNaN - 1;
const int dstBits = sizeof(DST_T) * 8;
const int dstExpBits = dstBits - DST_SIG_BITS - 1;
const int dstInfExp = (1 << dstExpBits) - 1;
const int dstExpBias = dstInfExp >> 1;
const DST_REP_T dstMinNormal = DST_REP_T(1) << DST_SIG_BITS;
union SrcExchangeType {
SRC_T f;
SRC_REP_T i;
};
SrcExchangeType src_rep;
src_rep.f = a;
const SRC_REP_T aRep = src_rep.i;
const SRC_REP_T aAbs = aRep & srcAbsMask;
const SRC_REP_T s |
ign = aRep & srcSignMask;
DST_REP_T absResult;
if ((SRC_REP_T)(aAbs - srcMinNormal) < srcInfinity - srcMinNormal) {
absResult = (DST_REP_T)aAbs << (DST_SIG_BITS - SRC_SIG_BITS);
absResult += (DST_REP_T)(dstExpBias - srcExpBias) << DST_SIG_BITS;
}
else if (aAbs >= srcInfinity) {
absResult = (DST_REP_T)dstInfExp << DST_SIG_BITS;
absResult |= (DST_REP_T)(aAbs & srcQNaN) << (DST_SIG_BITS - SRC_SIG_BITS);
absResult |= (DST_REP_T)(aAbs & srcNaNCode) << (DST_SIG_BITS - SRC_SIG_BITS);
} else if (aAbs) {
const int scale = __clz(aAbs) - __clz(srcMinNormal);
absResult = (DST_REP_T)aAbs << (DST_SIG_BITS - SRC_SIG_BITS + scale);
absResult ^= dstMinNormal;
const int resultExponent = dstExpBias - srcExpBias - scale + 1;
absResult |= (DST_REP_T)resultExponent << DST_SIG_BITS;
} else {
absResult = 0;
}
const DST_REP_T result = absResult | (DST_REP_T)sign << (dstBits - srcBits);
union DstExchangeType {
DST_T f;
DST_REP_T i;
};
DstExchangeType dst_rep;
dst_rep.i = result;
return dst_rep.f;
} |
/*
* Library: libcrc
* File: include/checksum.h
* Author: Lammert Bies
*
* This file is licensed under the MIT License as stated below
*
* Copyright (c) 1999-2018 Lammert Bies
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* Description
* -----------
* The headerfile include/checksum.h contains the definitions and prototypes
* for routines that can be used to calculate several kinds of checksums.
*/
extern "C" {
/*
*
*
* The constants of the form CRC_POLY_xxxx define the polynomials for some well
* known CRC calculations.
*/
/*
*
*
* The constants of the form CRC_START_xxxx define the values that are used for
* initialization of a CRC value for common used calculation methods.
*/
/*
* Prototype list of global functions
*/
unsigned char* checksum_NMEA(const unsigned char* input_str, unsigned char* result);
uint8_t crc_8(const unsigned char* input_str, size_t num_bytes);
uint16_t crc_16(const unsigned char* input_str, size_t num_bytes);
uint |
32_t crc_32(const unsigned char* input_str, size_t num_bytes);
uint64_t crc_64_ecma(const unsigned char* input_str, size_t num_bytes);
uint64_t crc_64_we(const unsigned char* input_str, size_t num_bytes);
uint16_t crc_ccitt_1d0f(const unsigned char* input_str, size_t num_bytes);
uint16_t crc_ccitt_ffff(const unsigned char* input_str, size_t num_bytes);
uint16_t crc_dnp(const unsigned char* input_str, size_t num_bytes);
uint16_t crc_kermit(const unsigned char* input_str, size_t num_bytes);
uint16_t crc_modbus(const unsigned char* input_str, size_t num_bytes);
uint16_t crc_sick(const unsigned char* input_str, size_t num_bytes);
uint16_t crc_xmodem(const unsigned char* input_str, size_t num_bytes);
uint8_t update_crc_8(uint8_t crc, unsigned char c);
uint16_t update_crc_16(uint16_t crc, unsigned char c);
uint32_t update_crc_32(uint32_t crc, unsigned char c);
uint64_t update_crc_64_ecma(uint64_t crc, unsigned char c);
uint16_t update_crc_ccitt(uint16_t crc, unsigned char c);
uint16_t update_crc_dnp(uint16_t crc, unsigned char c);
uint16_t update_crc_kermit(uint16_t crc, unsigned char c);
uint16_t update_crc_sick(uint16_t crc, unsigned char c, unsigned char prev_byte);
/*
* Global CRC lookup tables
*/
extern const uint32_t crc_tab32[];
extern const uint64_t crc_tab64[];
} |
/*
* Library: libcrc
* File: src/crcccitt.c
* Author: Lammert Bies
*
* This file is licensed under the MIT License as stated below
*
* Copyright (c) 1999-2016 Lammert Bies
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* Description
* -----------
* The module src/crcccitt.c contains routines which are used to calculate the
* CCITT CRC values of a string of bytes.
*/
static uint16_t crc_ccitt_generic(const unsigned char* input_str, size_t num_bytes,
uint16_t start_value);
/*
* uint16_t crc_xmodem( const unsigned char *input_str, size_t num_bytes );
*
* The function crc_xmodem() performs a one-pass calculation of an X-Modem CRC
* for a byte string that has been passed as a parameter.
*/
uint16_t crc_xmodem(const unsigned char* input_str, size_t num_bytes) {
return crc_ccitt_generic(input_str, num_bytes, CRC_START_XMODEM);
} /* crc_xmodem */
/*
* uint16_t crc_ccitt_1d0f( const unsigned char *input_str, size_t num_bytes );
*
* The func |
tion crc_ccitt_1d0f() performs a one-pass calculation of the CCITT
* CRC for a byte string that has been passed as a parameter. The initial value
* 0x1d0f is used for the CRC.
*/
uint16_t crc_ccitt_1d0f(const unsigned char* input_str, size_t num_bytes) {
return crc_ccitt_generic(input_str, num_bytes, CRC_START_CCITT_1D0F);
} /* crc_ccitt_1d0f */
/*
* uint16_t crc_ccitt_ffff( const unsigned char *input_str, size_t num_bytes );
*
* The function crc_ccitt_ffff() performs a one-pass calculation of the CCITT
* CRC for a byte string that has been passed as a parameter. The initial value
* 0xffff is used for the CRC.
*/
uint16_t crc_ccitt_ffff(const unsigned char* input_str, size_t num_bytes) {
return crc_ccitt_generic(input_str, num_bytes, CRC_START_CCITT_FFFF);
} /* crc_ccitt_ffff */
/*
* static uint16_t crc_ccitt_generic( const unsigned char *input_str, size_t num_bytes, uint16_t
* start_value );
*
* The function crc_ccitt_generic() is a generic implementation of the CCITT
* algorithm for a one-pass calculation of the CRC for a byte string. The
* function accepts an initial start value for the crc.
*/
static uint16_t crc_ccitt_generic(const unsigned char* input_str, size_t num_bytes,
uint16_t start_value) {
uint16_t crc;
const unsigned char* ptr;
size_t a;
crc = start_value;
ptr = input_str;
if (ptr != NULL)
for (a = 0; a < num_bytes; a++) {
crc = (crc << 8) ^ crc_tabccitt[((crc >> 8) ^ (uint16_t)*ptr++) & 0x00FF];
}
return crc;
} /* crc_ccitt_generic */
/*
* uint16_t update_crc_ccitt( uint16_t crc, unsigned char c );
*
* The function update_crc_ccitt() calculates a new CRC-CCITT value based on
* the previous value of the CRC and the next byte of the data to be checked.
*/
uint16_t update_crc_ccitt(uint16_t crc, unsigned char c) {
return (crc << 8) ^ crc_tabccitt[((crc >> 8) ^ (uint16_t)c) & 0x00FF];
} /* update_crc_ccitt */ |
/*
* Copyright 2009-2010 Cybozu Labs, Inc.
* Copyright 2011-2014 Kazuho Oku
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
extern "C" {
}
(defined(_MSC_VER) && _MSC_VER >= 1600)
extern "C" {
}
do { \
if (!(e)) throw std::runtime_error(
} while (0)
do { \
if (!(e)) std::abort(); \
} while (0)
namespace picojson {
enum {
null_type,
boolean_type,
number_type,
string_type,
array_type,
object_type
,
int64_type
};
enum { INDENT_WIDTH = 2 }; |
struct null {}; |
class value {
public:
typedef std::vector<value> array;
typedef std::unordered_map<std::string, value> object;
union _storage {
bool boolean_;
double number_;
int64_t int64_;
std::string* string_;
array* array_;
object* object_;
};
protected:
int type_;
_storage u_;
public:
value();
value(int type, bool);
explicit value(bool b);
explicit value(int64_t i);
explicit value(double n);
explicit value(const std::string& s);
explicit value(const array& a);
explicit value(const object& o);
explicit value(std::string&& s);
explicit value(array&& a);
explicit value(object&& o);
explicit value(const char* s);
value(const char* s, size_t len);
~value();
value(const value& x);
value& operator=(const value& x);
value(value&& x) PICOJSON_NOEXCEPT;
value& operator=(value&& x) PICOJSON_NOEXCEPT;
void swap(value& x) PICOJSON_NOEXCEPT;
template <typename T>
bool is() const;
template <typename T>
const T& get() const;
template <typename T>
T& get();
template <typename T>
void set(const T&);
template <typename T>
void set(T&&);
bool evaluate_as_boolean() const;
const value& get(const size_t idx) const;
const value& get(const std::string& key) const;
value& get(const size_t idx);
value& get(const std::string& key);
bool contains(const size_t idx) const;
bool contains(const std::string& key) const;
std::string to_str() const;
template <typename Iter>
void serialize(Iter os, bool prettify = false) const;
std::string serialize(bool prettify = false) const;
private:
template <typename T>
value(const T*);
template <typename Iter>
static void _indent(Iter os, int indent);
template <typename Iter>
void _serialize(Iter os, int indent) const;
std::string _serialize(int indent) const;
void clear();
};
typedef value::array array;
typedef value::object object;
inline value::value() : type_(null_type), u_() {}
inline value::value(int type, bool) : type_(type), u_() {
sw |
itch (type) {
case p
u_.p = v; \
break
INIT(boolean_, false);
INIT(number_, 0.0);
INIT(int64_, 0);
INIT(string_, new std::string());
INIT(array_, new array());
INIT(object_, new object());
default:
break;
}
}
inline value::value(bool b) : type_(boolean_type), u_() { u_.boolean_ = b; }
inline value::value(int64_t i) : type_(int64_type), u_() { u_.int64_ = i; }
inline value::value(double n) : type_(number_type), u_() {
if (
!_finite(n)
std::isnan(n) || std::isinf(n)
isnan(n) || isinf(n)
) {
throw std::overflow_error("");
std::abort();
}
u_.number_ = n;
}
inline value::value(const std::string& s) : type_(string_type), u_() {
u_.string_ = new std::string(s);
}
inline value::value(const array& a) : type_(array_type), u_() { u_.array_ = new array(a); }
inline value::value(const object& o) : type_(object_type), u_() { u_.object_ = new object(o); }
inline value::value(std::string&& s) : type_(string_type), u_() {
u_.string_ = new std::string(std::move(s));
}
inline value::value(array&& a) : type_(array_type), u_() { u_.array_ = new array(std::move(a)); }
inline value::value(object&& o) : type_(object_type), u_() {
u_.object_ = new object(std::move(o));
}
inline value::value(const char* s) : type_(string_type), u_() { u_.string_ = new std::string(s); }
inline value::value(const char* s, size_t len) : type_(string_type), u_() {
u_.string_ = new std::string(s, len);
}
inline void value::clear() {
switch (type_) {
case p
delete u_.p; \
break
DEINIT(string_);
DEINIT(array_);
DEINIT(object_);
default:
break;
}
}
inline value::~value() { clear(); }
inline value::value(const value& x) : type_(x.type_), u_() {
switch (type_) {
case p
u_.p = v; \
break
INIT(string_, new std::string(*x.u_.string_));
INIT(array_, new array(*x.u_.array_));
INIT(object_, new object(*x.u_.object_));
default:
u_ = x.u_;
break;
}
}
inline value& v |
alue::operator=(const value& x) {
if (this != &x) {
value t(x);
swap(t);
}
return *this;
}
inline value::value(value&& x) PICOJSON_NOEXCEPT : type_(null_type), u_() { swap(x); }
inline value& value::operator=(value&& x) PICOJSON_NOEXCEPT {
swap(x);
return *this;
}
inline void value::swap(value& x) PICOJSON_NOEXCEPT {
std::swap(type_, x.type_);
std::swap(u_, x.u_);
}
template <> \
inline bool value::is<ctype>() const { \
return type_ == jtype
}
IS(null, null)
IS(bool, boolean)
IS(int64_t, int64)
IS(std::string, string)
IS(array, array)
IS(object, object)
template <>
inline bool value::is<double>() const {
return type_ == number_type
|| type_ == int64_type
;
}
template <> \
inline const ctype& value::get<ctype>() const { \
PICOJSON_ASSERT("type mismatch! call is<type>() before get<type>()" && is<ctype>()); \
return var; \
} \
template <> \
inline ctype& value::get<ctype>() { \
PICOJSON_ASSERT("type mismatch! call is<type>() before get<type>()" && is<ctype>()); \
return var; \
}
GET(bool, u_.boolean_)
GET(std::string, *u_.string_)
GET(array, *u_.array_)
GET(object, *u_.object_)
GET(double, (type_ == int64_type && (const_cast<value*>(this)->type_ = number_type,
const_cast<value*>(this)->u_.number_ = u_.int64_),
u_.number_))
GET(int64_t, u_.int64_)
GET(double, u_.number_)
template <> \
inline void value::set<ctype>(const ctype& _val) { \ |
clear(); \
type_ = jtype
setter \
}
SET(bool, boolean, u_.boolean_ = _val;)
SET(std::string, string, u_.string_ = new std::string(_val);)
SET(array, array, u_.array_ = new array(_val);)
SET(object, object, u_.object_ = new object(_val);)
SET(double, number, u_.number_ = _val;)
SET(int64_t, int64, u_.int64_ = _val;)
template <> \
inline void value::set<ctype>(ctype && _val) { \
clear(); \
type_ = jtype
setter \
}
MOVESET(std::string, string, u_.string_ = new std::string(std::move(_val));)
MOVESET(array, array, u_.array_ = new array(std::move(_val));)
MOVESET(object, object, u_.object_ = new object(std::move(_val));)
inline bool value::evaluate_as_boolean() const {
switch (type_) {
case null_type:
return false;
case boolean_type:
return u_.boolean_;
case number_type:
return u_.number_ != 0;
case int64_type:
return u_.int64_ != 0;
case string_type:
return !u_.string_->empty();
default:
return true;
}
}
inline const value& value::get(const size_t idx) const {
static value s_null;
PICOJSON_ASSERT(is<array>());
return idx < u_.array_->size() ? (*u_.array_)[idx] : s_null;
}
inline value& value::get(const size_t idx) {
static value s_null;
PICOJSON_ASSERT(is<array>());
return idx < u_.array_->size() ? (*u_.array_)[idx] : s_null;
}
inline const value& value::get(const std::string& key) const {
static value s_null;
PICOJSON_ASSERT(is<object>());
object::const_iterator i = u_.object_->find(key);
return i != u_.object_->end() ? i->second : s_null;
}
inline value& value::get(const std::string& key) {
static value s_null;
PICOJSON_ASSERT(is<object>());
object::iterator i = u_.object_->find(key);
return i != u_.object_->end() ? i->second : s_null;
}
inline bool value::contains(const size_t idx) const { |
PICOJSON_ASSERT(is<array>());
return idx < u_.array_->size();
}
inline bool value::contains(const std::string& key) const {
PICOJSON_ASSERT(is<object>());
object::const_iterator i = u_.object_->find(key);
return i != u_.object_->end();
}
inline std::string value::to_str() const {
switch (type_) {
case null_type:
return "null";
case boolean_type:
return u_.boolean_ ? "true" : "false";
case int64_type: {
char buf[sizeof("-9223372036854775808")];
SNPRINTF(buf, sizeof(buf), "%" PRId64, u_.int64_);
return buf;
}
case number_type: {
char buf[256];
double tmp;
SNPRINTF(buf, sizeof(buf),
fabs(u_.number_) < (1ULL << 53) && modf(u_.number_, &tmp) == 0 ? "%.f" : "%.17g",
u_.number_);
char* decimal_point = localeconv()->decimal_point;
if (strcmp(decimal_point, ".") != 0) {
size_t decimal_point_len = strlen(decimal_point);
for (char* p = buf; *p != '\0'; ++p) {
if (strncmp(p, decimal_point, decimal_point_len) == 0) {
return std::string(buf, p) + "." + (p + decimal_point_len);
}
}
}
return buf;
}
case string_type:
return *u_.string_;
case array_type:
return "array";
case object_type:
return "object";
default:
PICOJSON_ASSERT(0);
__assume(0);
}
return std::string();
}
template <typename Iter>
void copy(const std::string& s, Iter oi) {
std::copy(s.begin(), s.end(), oi);
}
template <typename Iter> |
struct serialize_str_char {
Iter oi;
void operator()(char c) {
switch (c) {
case val: \
copy(sym, oi); \
break
MAP('"', "\\\"");
MAP('\\', "\\\\");
MAP('/', "\\/");
MAP('\b', "\\b");
MAP('\f', "\\f");
MAP('\n', "\\n");
MAP('\r', "\\r");
MAP('\t', "\\t");
default:
if (static_cast<unsigned char>(c) < 0x20 || c == 0x7f) {
char buf[7];
SNPRINTF(buf, sizeof(buf), "\\u%04x", c & 0xff);
copy(buf, buf + 6, oi);
} else {
*oi++ = c;
}
break;
}
}
};
template <typename Iter>
void serialize_str(const std::string& s, Iter oi) {
*oi++ = '"';
serialize_str_char<Iter> process_char = {oi};
std::for_each(s.begin(), s.end(), process_char);
*oi++ = '"';
}
template <typename Iter>
void value::serialize(Iter oi, bool prettify) const {
return _serialize(oi, prettify ? 0 : -1);
}
inline std::string value::serialize(bool prettify) const { return _serialize(prettify ? 0 : -1); }
template <typename Iter>
void value::_indent(Iter oi, int indent) {
*oi++ = '\n';
for (int i = 0; i < indent * INDENT_WIDTH; ++i) {
*oi++ = ' ';
}
}
template <typename Iter>
void value::_serialize(Iter oi, int indent) const {
switch (type_) {
case string_type:
serialize_str(*u_.string_, oi);
break;
case array_type: {
*oi++ = '[';
if (indent != -1) {
++indent;
}
for (array::const_iterator i = u_.array_->begin(); i != u_.array_->end(); ++i) {
if (i != u_.array_->begin()) {
*oi++ = ',';
}
if (indent != -1) {
_indent(oi, indent);
}
i->_serialize(oi, indent);
}
if (indent != -1) {
--indent;
if (!u_.array_->empty()) {
_indent(oi, indent);
}
}
*oi++ = ']';
break;
}
case object_type: {
*oi++ = '{';
if (indent != -1) {
++indent;
}
for (object::const_iterator i = u_.object_- |
>begin(); i != u_.object_->end(); ++i) {
if (i != u_.object_->begin()) {
*oi++ = ',';
}
if (indent != -1) {
_indent(oi, indent);
}
serialize_str(i->first, oi);
*oi++ = ':';
if (indent != -1) {
*oi++ = ' ';
}
i->second._serialize(oi, indent);
}
if (indent != -1) {
--indent;
if (!u_.object_->empty()) {
_indent(oi, indent);
}
}
*oi++ = '}';
break;
}
default:
copy(to_str(), oi);
break;
}
if (indent == 0) {
*oi++ = '\n';
}
}
inline std::string value::_serialize(int indent) const {
std::string s;
_serialize(std::back_inserter(s), indent);
return s;
}
template <typename Iter> |
class input {
protected:
Iter cur_, end_;
bool consumed_;
int line_;
public:
input(const Iter& first, const Iter& last)
: cur_(first), end_(last), consumed_(false), line_(1) {}
int getc() {
if (consumed_) {
if (*cur_ == '\n') {
++line_;
}
++cur_;
}
if (cur_ == end_) {
consumed_ = false;
return -1;
}
consumed_ = true;
return *cur_ & 0xff;
}
void ungetc() { consumed_ = false; }
Iter cur() const {
if (consumed_) {
input<Iter>* self = const_cast<input<Iter>*>(this);
self->consumed_ = false;
++self->cur_;
}
return cur_;
}
int line() const { return line_; }
void skip_ws() {
while (1) {
int ch = getc();
if (!(ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r')) {
ungetc();
break;
}
}
}
bool expect(const int expected) {
skip_ws();
if (getc() != expected) {
ungetc();
return false;
}
return true;
}
bool match(const std::string& pattern) {
for (std::string::const_iterator pi(pattern.begin()); pi != pattern.end(); ++pi) {
if (getc() != *pi) {
ungetc();
return false;
}
}
return true;
}
};
template <typename Iter>
inline int _parse_quadhex(input<Iter>& in) {
int uni_ch = 0, hex;
for (int i = 0; i < 4; i++) {
if ((hex = in.getc()) == -1) {
return -1;
}
if ('0' <= hex && hex <= '9') {
hex -= '0';
} else if ('A' <= hex && hex <= 'F') {
hex -= 'A' - 0xa;
} else if ('a' <= hex && hex <= 'f') {
hex -= 'a' - 0xa;
} else {
in.ungetc();
return -1;
}
uni_ch = uni_ch * 16 + hex;
}
return uni_ch;
}
template <typename String, typename Iter>
inline bool _parse_codepoint(String& out, input<Iter>& in) {
int uni_ch;
if ((uni_ch = _parse_quadhex(in)) == -1) {
return false;
}
if (0xd800 <= uni_ch && uni_ch <= 0xdfff) {
if (0xdc00 <= uni_ch) {
return false;
}
if (in.getc() != '\\' || in. |
getc() != 'u') {
in.ungetc();
return false;
}
int second = _parse_quadhex(in);
if (!(0xdc00 <= second && second <= 0xdfff)) {
return false;
}
uni_ch = ((uni_ch - 0xd800) << 10) | ((second - 0xdc00) & 0x3ff);
uni_ch += 0x10000;
}
if (uni_ch < 0x80) {
out.push_back(static_cast<char>(uni_ch));
} else {
if (uni_ch < 0x800) {
out.push_back(static_cast<char>(0xc0 | (uni_ch >> 6)));
} else {
if (uni_ch < 0x10000) {
out.push_back(static_cast<char>(0xe0 | (uni_ch >> 12)));
} else {
out.push_back(static_cast<char>(0xf0 | (uni_ch >> 18)));
out.push_back(static_cast<char>(0x80 | ((uni_ch >> 12) & 0x3f)));
}
out.push_back(static_cast<char>(0x80 | ((uni_ch >> 6) & 0x3f)));
}
out.push_back(static_cast<char>(0x80 | (uni_ch & 0x3f)));
}
return true;
}
template <typename String, typename Iter>
inline bool _parse_string(String& out, input<Iter>& in) {
while (1) {
int ch = in.getc();
if (ch < ' ') {
in.ungetc();
return false;
} else if (ch == '"') {
return true;
} else if (ch == '\\') {
if ((ch = in.getc()) == -1) {
return false;
}
switch (ch) {
case sym: \
out.push_back(val); \
break
MAP('"', '\"');
MAP('\\', '\\');
MAP('/', '/');
MAP('b', '\b');
MAP('f', '\f');
MAP('n', '\n');
MAP('r', '\r');
MAP('t', '\t');
case 'u':
if (!_parse_codepoint(out, in)) {
return false;
}
break;
default:
return false;
}
} else {
out.push_back(static_cast<char>(ch));
}
}
return false;
}
template <typename Context, typename Iter>
inline bool _parse_array(Context& ctx, input<Iter>& in) {
if (!ctx.parse_array_start()) {
return false;
}
size_t idx = 0;
if (in.expect(']')) {
return ctx.parse_array_stop(idx);
}
do {
if (!ctx.parse_array_item(in, idx)) {
return fals |
e;
}
idx++;
} while (in.expect(','));
return in.expect(']') && ctx.parse_array_stop(idx);
}
template <typename Context, typename Iter>
inline bool _parse_object(Context& ctx, input<Iter>& in) {
if (!ctx.parse_object_start()) {
return false;
}
if (in.expect('}')) {
return true;
}
do {
std::string key;
if (!in.expect('"') || !_parse_string(key, in) || !in.expect(':')) {
return false;
}
if (!ctx.parse_object_item(in, key)) {
return false;
}
} while (in.expect(','));
return in.expect('}');
}
template <typename Iter>
inline std::string _parse_number(input<Iter>& in) {
std::string num_str;
while (1) {
int ch = in.getc();
if (('0' <= ch && ch <= '9') || ch == '+' || ch == '-' || ch == 'e' || ch == 'E') {
num_str.push_back(static_cast<char>(ch));
} else if (ch == '.') {
num_str += localeconv()->decimal_point;
num_str.push_back('.');
} else {
in.ungetc();
break;
}
}
return num_str;
}
template <typename Context, typename Iter>
inline bool _parse(Context& ctx, input<Iter>& in) {
in.skip_ws();
int ch = in.getc();
switch (ch) {
case ch: \
if (in.match(text) && op) { \
return true; \
} else { \
return false; \
}
IS('n', "ull", ctx.set_null());
IS('f', "alse", ctx.set_bool(false));
IS('t', "rue", ctx.set_bool(true));
case '"':
return ctx.parse_string(in);
case '[':
return _parse_array(ctx, in);
case '{':
return _parse_object(ctx, in);
default:
if (('0' <= ch && ch <= '9') || ch == '-') {
double f;
char* endp;
in.ungetc();
std::string num_str(_parse_number(in));
if (num_str.empty()) {
return false;
}
{
errno = 0;
intmax_t ival = strtoimax(num_str.c_str(), &endp, 10);
if (errno == 0 && std::numeric_limits<int64_t>::min() <= ival &&
ival <= st |
d::numeric_limits<int64_t>::max() &&
endp == num_str.c_str() + num_str.size()) {
ctx.set_int64(ival);
return true;
}
}
f = strtod(num_str.c_str(), &endp);
if (endp == num_str.c_str() + num_str.size()) {
ctx.set_number(f);
return true;
}
return false;
}
break;
}
in.ungetc();
return false;
} |
class deny_parse_context {
public:
bool set_null() { return false; }
bool set_bool(bool) { return false; }
bool set_int64(int64_t) { return false; }
bool set_number(double) { return false; }
template <typename Iter>
bool parse_string(input<Iter>&) {
return false;
}
bool parse_array_start() { return false; }
template <typename Iter>
bool parse_array_item(input<Iter>&, size_t) {
return false;
}
bool parse_array_stop(size_t) { return false; }
bool parse_object_start() { return false; }
template <typename Iter>
bool parse_object_item(input<Iter>&, const std::string&) {
return false;
}
}; |
class default_parse_context {
protected:
value* out_;
public:
default_parse_context(value* out) : out_(out) {}
bool set_null() {
*out_ = value();
return true;
}
bool set_bool(bool b) {
*out_ = value(b);
return true;
}
bool set_int64(int64_t i) {
*out_ = value(i);
return true;
}
bool set_number(double f) {
*out_ = value(f);
return true;
}
template <typename Iter>
bool parse_string(input<Iter>& in) {
*out_ = value(string_type, false);
return _parse_string(out_->get<std::string>(), in);
}
bool parse_array_start() {
*out_ = value(array_type, false);
return true;
}
template <typename Iter>
bool parse_array_item(input<Iter>& in, size_t) {
array& a = out_->get<array>();
a.push_back(value());
default_parse_context ctx(&a.back());
return _parse(ctx, in);
}
bool parse_array_stop(size_t) { return true; }
bool parse_object_start() {
*out_ = value(object_type, false);
return true;
}
template <typename Iter>
bool parse_object_item(input<Iter>& in, const std::string& key) {
object& o = out_->get<object>();
default_parse_context ctx(&o[key]);
return _parse(ctx, in);
}
private:
default_parse_context(const default_parse_context&);
default_parse_context& operator=(const default_parse_context&);
}; |
class null_parse_context {
public: |
struct dummy_str {
void push_back(int) {}
};
public:
null_parse_context() {}
bool set_null() { return true; }
bool set_bool(bool) { return true; }
bool set_int64(int64_t) { return true; }
bool set_number(double) { return true; }
template <typename Iter>
bool parse_string(input<Iter>& in) {
dummy_str s;
return _parse_string(s, in);
}
bool parse_array_start() { return true; }
template <typename Iter>
bool parse_array_item(input<Iter>& in, size_t) {
return _parse(*this, in);
}
bool parse_array_stop(size_t) { return true; }
bool parse_object_start() { return true; }
template <typename Iter>
bool parse_object_item(input<Iter>& in, const std::string&) {
return _parse(*this, in);
}
private:
null_parse_context(const null_parse_context&);
null_parse_context& operator=(const null_parse_context&);
};
template <typename Iter>
inline std::string parse(value& out, Iter& pos, const Iter& last) {
std::string err;
pos = parse(out, pos, last, &err);
return err;
}
template <typename Context, typename Iter>
inline Iter _parse(Context& ctx, const Iter& first, const Iter& last, std::string* err) {
input<Iter> in(first, last);
if (!_parse(ctx, in) && err != NULL) {
char buf[64];
SNPRINTF(buf, sizeof(buf), "syntax error at line %d near: ", in.line());
*err = buf;
while (1) {
int ch = in.getc();
if (ch == -1 || ch == '\n') {
break;
} else if (ch >= ' ') {
err->push_back(static_cast<char>(ch));
}
}
}
return in.cur();
}
template <typename Iter>
inline Iter parse(value& out, const Iter& first, const Iter& last, std::string* err) {
default_parse_context ctx(&out);
return _parse(ctx, first, last, err);
}
inline std::string parse(value& out, const std::string& s) {
std::string err;
parse(out, s.begin(), s.end(), &err);
return err;
}
inline std::string parse(value& out, std::istream& is) {
std::string err;
parse(out, std::istreambuf_iterator<char>(is.rdbuf()), std::istreamb |
uf_iterator<char>(), &err);
return err;
}
template <typename T> |
struct last_error_t {
static std::string s;
};
template <typename T>
std::string last_error_t<T>::s;
inline void set_last_error(const std::string& s) { last_error_t<bool>::s = s; }
inline const std::string& get_last_error() { return last_error_t<bool>::s; }
inline bool operator==(const value& x, const value& y) {
if (x.is<null>()) return y.is<null>();
if (x.is<type>()) return y.is<type>() && x.get<type>() == y.get<type>()
PICOJSON_CMP(bool);
PICOJSON_CMP(double);
PICOJSON_CMP(std::string);
PICOJSON_CMP(array);
PICOJSON_CMP(object);
PICOJSON_ASSERT(0);
__assume(0);
return false;
}
inline bool operator!=(const value& x, const value& y) { return !(x == y); }
}
namespace std {
template <>
inline void swap(picojson::value& x, picojson::value& y) {
x.swap(y);
}
}
inline std::istream& operator>>(std::istream& is, picojson::value& x) {
picojson::set_last_error(std::string());
const std::string err(picojson::parse(x, is));
if (!err.empty()) {
picojson::set_last_error(err);
is.setstate(std::ios::failbit);
}
return is;
}
inline std::ostream& operator<<(std::ostream& os, const picojson::value& x) {
x.serialize(std::ostream_iterator<char>(os));
return os;
} |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http:
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.tvm.android.androidcamerademo; |
import android.annotation.SuppressLint; |
import android.content.res.AssetManager; |
import android.graphics.Bitmap; |
import android.graphics.Canvas; |
import android.graphics.Matrix; |
import android.media.Image; |
import android.os.AsyncTask; |
import android.os.Bundle; |
import android.os.SystemClock; |
import android.util.Log; |
import android.util.Size; |
import android.view.LayoutInflater; |
import android.view.View; |
import android.view.ViewGroup; |
import android.widget.ArrayAdapter; |
import android.widget.ListView; |
import androidx.annotation.NonNull; |
import androidx.annotation.Nullable; |
import androidx.appcompat.widget.AppCompatTextView; |
import androidx.camera.core.Camera; |
import androidx.camera.core.CameraSelector; |
import androidx.camera.core.ImageAnalysis; |
import androidx.camera.core.ImageProxy; |
import androidx.camera.core.Preview; |
import androidx.camera.lifecycle.ProcessCameraProvider; |
import androidx.camera.view.PreviewView; |
import androidx.core.content.ContextCompat; |
import androidx.fragment.app.Fragment; |
import androidx.renderscript.Allocation; |
import androidx.renderscript.Element; |
import androidx.renderscript.RenderScript; |
import androidx.renderscript.Script; |
import androidx.renderscript.Type; |
import com.google.common.util.concurrent.ListenableFuture; |
import org.apache.tvm.Function; |
import org.apache.tvm.Module; |
import org.apache.tvm.NDArray; |
import org.apache.tvm.Device; |
import org.apache.tvm.TVMType; |
import org.apache.tvm.TVMValue; |
import org.json.JSONException; |
import org.json.JSONObject; |
import java.io.File; |
import java.io.FileOutputStream; |
import java.io.IOException; |
import java.io.InputStream; |
import java.nio.ByteBuffer; |
import java.util.PriorityQueue; |
import java.util.concurrent.ExecutionException; |
import java.util.concurrent.LinkedBlockingQueue; |
import java.util.concurrent.Semaphore; |
import java.util.concurrent.ThreadPoolExecutor; |
import java.util.concurrent.TimeUnit;
public class Camera2BasicFragment extends Fragment {
private static final String TAG = Camera2BasicFragment.class.getSimpleName();
private static final int OUTPUT_INDEX = 0;
private static final int IMG_CHANNEL = 3;
private static final boolean EXE_GPU = false;
private static final int MODEL_INPUT_SIZE = 224;
private static final String MODEL_CL_LIB_FILE = "deploy_lib_opencl.so";
private static final String MODEL_CPU_LIB_FILE = "deploy_lib_cpu.so";
private static final String MODEL_GRAPH_FILE = "deploy_graph.json";
private static final String MODEL_PARAM_FILE = "deploy_param.params";
private static final String MODEL_LABEL_FILE = "image_net_labels.json";
private static final String MODELS = "models";
private static String INPUT_NAME = "input_1";
private static String[] models;
private static String mCurModel = "";
private final float[] mCHW = new float[MODEL_INPUT_SIZE * MODEL_INPUT_SIZE * IMG_CHANNEL];
private final float[] mCHW2 = new float[MODEL_INPUT_SIZE * MODEL_INPUT_SIZE * IMG_CHANNEL];
private final Semaphore isProcessingDone = new Semaphore(1);
private final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
3,
3,
1,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>()
);
private RenderScript rs;
private ScriptC_yuv420888 mYuv420;
private boolean mRunClassifier = false;
private AppCompatTextView mResultView;
private AppCompatTextView mInfoView;
private ListView mModelView;
private AssetManager assetManager;
private Module graphExecutorModule;
private JSONObject labels;
private ListenableFuture<ProcessCameraProvider> cameraProviderFuture;
private PreviewView previewView;
private ImageAnalysis imageAnalysis;
static Camera2BasicFragment newInstance() {
return new Camera2BasicFragment();
}
private static Matrix getTransformationMatrix(
fi |
nal int srcWidth,
final int srcHeight,
final int dstWidth,
final int dstHeight,
final int applyRotation,
final boolean maintainAspectRatio) {
final Matrix matrix = new Matrix();
if (applyRotation != 0) {
if (applyRotation % 90 != 0) {
Log.w(TAG, "Rotation of %d % 90 != 0 " + applyRotation);
}
matrix.postTranslate(-srcWidth / 2.0f, -srcHeight / 2.0f);
matrix.postRotate(applyRotation);
}
final boolean transpose = (Math.abs(applyRotation) + 90) % 180 == 0;
final int inWidth = transpose ? srcHeight : srcWidth;
final int inHeight = transpose ? srcWidth : srcHeight;
if (inWidth != dstWidth || inHeight != dstHeight) {
final float scaleFactorX = dstWidth / (float) inWidth;
final float scaleFactorY = dstHeight / (float) inHeight;
if (maintainAspectRatio) {
final float scaleFactor = Math.max(scaleFactorX, scaleFactorY);
matrix.postScale(scaleFactor, scaleFactor);
} else {
matrix.postScale(scaleFactorX, scaleFactorY);
}
}
if (applyRotation != 0) {
matrix.postTranslate(dstWidth / 2.0f, dstHeight / 2.0f);
}
return matrix;
}
private String[] getModels() {
String[] models;
try {
models = getActivity().getAssets().list(MODELS);
} catch (IOException e) {
return null;
}
return models;
}
@SuppressLint("DefaultLocale")
private String[] inference(float[] chw) {
NDArray inputNdArray = NDArray.empty(new long[]{1, IMG_CHANNEL, MODEL_INPUT_SIZE, MODEL_INPUT_SIZE}, new TVMType("float32"));
inputNdArray.copyFrom(chw);
Function setInputFunc = graphExecutorModule.getFunction("set_inpu |
t");
setInputFunc.pushArg(INPUT_NAME).pushArg(inputNdArray).invoke();
inputNdArray.release();
setInputFunc.release();
Function runFunc = graphExecutorModule.getFunction("run");
runFunc.invoke();
runFunc.release();
NDArray outputNdArray = NDArray.empty(new long[]{1, 1000}, new TVMType("float32"));
Function getOutputFunc = graphExecutorModule.getFunction("get_output");
getOutputFunc.pushArg(OUTPUT_INDEX).pushArg(outputNdArray).invoke();
float[] output = outputNdArray.asFloatArray();
outputNdArray.release();
getOutputFunc.release();
if (null != output) {
String[] results = new String[5];
PriorityQueue<Integer> pq = new PriorityQueue<>(1000, (Integer idx1, Integer idx2) -> output[idx1] > output[idx2] ? -1 : 1);
for (int j = 0; j < output.length; ++j) {
pq.add(j);
}
for (int l = 0; l < 5; l++) {
int idx = pq.poll();
if (idx < labels.length()) {
try {
results[l] = String.format("%.2f", output[idx]) + " : " + labels.getString(Integer.toString(idx));
} catch (JSONException e) {
Log.e(TAG, "index out of range", e);
}
} else {
results[l] = "???: unknown";
}
}
return results;
}
return new String[5];
}
private void updateActiveModel() {
Log.i(TAG, "updating active model...");
new LoadModelAsyncTask().execute();
}
@Override
public void onViewCreated(final View view, Bundle savedInstanceState) {
mResultView = view.findViewById(R.id.resultTextView);
mInfoView = view.findViewById(R.id.infoTextView);
mModelView = view.findViewById(R.id.modelListView);
if (assetManag |
er == null) {
assetManager = getActivity().getAssets();
}
mModelView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
models = getModels();
ArrayAdapter<String> modelAdapter =
new ArrayAdapter<>(
getContext(), R.layout.listview_row, R.id.listview_row_text, models);
mModelView.setAdapter(modelAdapter);
mModelView.setItemChecked(0, true);
mModelView.setOnItemClickListener(
(parent, view1, position, id) -> updateActiveModel());
new LoadModelAsyncTask().execute();
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
@Override
public void onDestroy() {
if (null != graphExecutorModule)
graphExecutorModule.release();
super.onDestroy();
}
/**
* Read file from assets and return byte array.
*
* @param assets The asset manager to be used to load assets.
* @param fileName The filepath of read file.
* @return byte[] file content
* @throws IOException
*/
private byte[] getBytesFromFile(AssetManager assets, String fileName) throws IOException {
InputStream is = assets.open(fileName);
int length = is.available();
byte[] bytes = new byte[length];
int offset = 0;
int numRead;
try {
while (offset < bytes.length
&& (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
offset += numRead;
}
} finally {
is.close();
}
if (offset < bytes.length) {
throw new IOException("Could not completely read file " + fileName);
}
return bytes;
}
/**
* Get application cache path where to place compiled functions.
*
* @param fileName library file name.
* @return String application cache folder path
* @throws IO |
Exception
*/
private String getTempLibFilePath(String fileName) throws IOException {
File tempDir = File.createTempFile("tvm4j_demo_", "");
if (!tempDir.delete() || !tempDir.mkdir()) {
throw new IOException("Couldn't create directory " + tempDir.getAbsolutePath());
}
return (tempDir + File.separator + fileName);
}
private Bitmap YUV_420_888_toRGB(Image image, int width, int height) {
Image.Plane[] planes = image.getPlanes();
ByteBuffer buffer = planes[0].getBuffer();
byte[] y = new byte[buffer.remaining()];
buffer.get(y);
buffer = planes[1].getBuffer();
byte[] u = new byte[buffer.remaining()];
buffer.get(u);
buffer = planes[2].getBuffer();
byte[] v = new byte[buffer.remaining()];
buffer.get(v);
int yRowStride = planes[0].getRowStride();
int uvRowStride = planes[1].getRowStride();
int uvPixelStride = planes[1].getPixelStride();
Type.Builder typeUcharY = new Type.Builder(rs, Element.U8(rs));
typeUcharY.setX(yRowStride).setY(height);
Allocation yAlloc = Allocation.createTyped(rs, typeUcharY.create());
yAlloc.copyFrom(y);
mYuv420.set_ypsIn(yAlloc);
Type.Builder typeUcharUV = new Type.Builder(rs, Element.U8(rs));
typeUcharUV.setX(u.length);
Allocation uAlloc = Allocation.createTyped(rs, typeUcharUV.create());
uAlloc.copyFrom(u);
mYuv420.set_uIn(uAlloc);
Allocation vAlloc = Allocation.createTyped(rs, typeUcharUV.create());
vAlloc.copyFrom(v);
mYuv420.set_vIn(vAlloc);
mYuv420.set_picWidth(width);
mYuv420.set_uvRowStride(uvRowStride);
mYuv420.set_uvPixelStride(uvPixelStride);
Bitmap outBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Allocation outAlloc = Allocation.createFromBitmap(rs, outBitmap, Allocation.MipmapControl.MIP |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.