Add WASM parser and Vue dissector UI.
Ship a working HexPigeon: typed binary parsing in Rust/WASM, a three-pane frontend, and unit tests covering the field types. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -0,0 +1,7 @@
|
||||
target/
|
||||
frontend/node_modules/
|
||||
frontend/dist/
|
||||
frontend/src/wasm/
|
||||
.cursor/
|
||||
.DS_Store
|
||||
*.local
|
||||
@@ -0,0 +1,20 @@
|
||||
.PHONY: wasm frontend dev build test clean
|
||||
|
||||
wasm:
|
||||
cd parser-wasm && wasm-pack build --target web --out-dir ../frontend/src/wasm
|
||||
|
||||
frontend:
|
||||
cd frontend && npm install
|
||||
|
||||
dev: wasm frontend
|
||||
cd frontend && npm run dev
|
||||
|
||||
build: wasm
|
||||
cd frontend && npm run build
|
||||
|
||||
test:
|
||||
cd parser-wasm && cargo test
|
||||
cd frontend && npm install && npm test
|
||||
|
||||
clean:
|
||||
rm -rf frontend/src/wasm frontend/dist parser-wasm/target
|
||||
@@ -1,2 +1,43 @@
|
||||
# HexPigeon
|
||||
|
||||
Paste a hex dump, describe the layout in JSON or YAML, get a field tree and a highlighted hex view.
|
||||
|
||||
The parser is Rust compiled to WASM. The UI is Vue 3.
|
||||
|
||||
## Layout
|
||||
|
||||
```
|
||||
parser-wasm/ binary types, endianness, bitflags, strings, CRC
|
||||
frontend/ schema editor, hex view, parsed tree
|
||||
```
|
||||
|
||||
Field types: `uint8/16/32/64`, `int8/16/32`, `float32/64`, `bitflags8/16`, `bytes`, `string_fixed`, `string_lp8`, `string_lp16`, `crc16`, `crc32`, `repeated`, `padding`.
|
||||
|
||||
## Run
|
||||
|
||||
Needs `wasm-pack`, a Rust toolchain with `wasm32-unknown-unknown`, and Node 22.
|
||||
|
||||
```bash
|
||||
nix-shell # optional
|
||||
make test
|
||||
make dev
|
||||
```
|
||||
|
||||
`make dev` builds the WASM module, installs frontend deps, and starts Vite on http://localhost:5173.
|
||||
|
||||
## Schema
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "Example Frame",
|
||||
"endian": "big",
|
||||
"fields": [
|
||||
{ "name": "magic", "type": "uint8" },
|
||||
{ "name": "len", "type": "uint8" },
|
||||
{ "name": "payload", "type": "string_fixed", "length": 5 },
|
||||
{ "name": "checksum", "type": "crc32", "checksum_range": [0, 11] }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Hex input is whitespace-insensitive. Hovering a field highlights its bytes; CRC fields report valid/invalid when `checksum_range` is set.
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>HexPigeon — Binary Protocol Dissector</title>
|
||||
<link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'><rect width='32' height='32' fill='%23161b22'/><text x='16' y='22' text-anchor='middle' font-family='monospace' font-size='14' fill='%2358a6ff'>HP</text></svg>" />
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
Generated
+2351
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"name": "hex-pigeon-frontend",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vue-tsc --noEmit && vite build",
|
||||
"preview": "vite preview",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest",
|
||||
"build:wasm": "cd ../parser-wasm && wasm-pack build --target web --out-dir ../frontend/src/wasm"
|
||||
},
|
||||
"dependencies": {
|
||||
"vue": "^3.4.0",
|
||||
"pinia": "^2.1.7",
|
||||
"@codemirror/view": "^6.26.3",
|
||||
"@codemirror/state": "^6.4.1",
|
||||
"@codemirror/lang-json": "^6.0.1",
|
||||
"@codemirror/theme-one-dark": "^6.1.2",
|
||||
"js-yaml": "^4.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vitejs/plugin-vue": "^5.0.4",
|
||||
"typescript": "^5.4.5",
|
||||
"vite": "^5.2.11",
|
||||
"vitest": "^2.1.8",
|
||||
"vue-tsc": "^2.0.13",
|
||||
"vite-plugin-wasm": "^3.3.0",
|
||||
"vite-plugin-top-level-await": "^1.4.4"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
<template>
|
||||
<div class="app">
|
||||
<header class="app-header">
|
||||
<div class="brand">
|
||||
<span class="logo">HexPigeon</span>
|
||||
<span class="subtitle">Binary Protocol Dissector</span>
|
||||
</div>
|
||||
<div class="header-actions">
|
||||
<button class="btn btn-primary" @click="store.runParse()" :disabled="!store.wasmReady">
|
||||
{{ store.wasmReady ? 'Parse' : 'Loading engine...' }}
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div v-if="store.wasmError" class="banner banner-error">
|
||||
{{ store.wasmError }}
|
||||
<small>Run <code>make wasm</code> then <code>make dev</code>.</small>
|
||||
</div>
|
||||
|
||||
<main class="panels">
|
||||
<aside class="panel panel-schema">
|
||||
<PanelHeader title="Schema">
|
||||
<select v-model="store.schemaFormat" class="format-select" aria-label="Schema format">
|
||||
<option value="json">JSON</option>
|
||||
<option value="yaml">YAML</option>
|
||||
</select>
|
||||
</PanelHeader>
|
||||
<SchemaEditor />
|
||||
</aside>
|
||||
|
||||
<section class="panel panel-hex">
|
||||
<PanelHeader title="Hex View">
|
||||
<span class="byte-count">{{ store.bytes.length }} bytes</span>
|
||||
</PanelHeader>
|
||||
<HexInput />
|
||||
<HexViewer />
|
||||
</section>
|
||||
|
||||
<aside class="panel panel-tree">
|
||||
<PanelHeader title="Parsed Fields">
|
||||
<span v-if="store.parseResult" class="byte-count">
|
||||
{{ store.parseResult.consumed_bytes }}/{{ store.parseResult.total_bytes }} B
|
||||
</span>
|
||||
</PanelHeader>
|
||||
<div v-if="store.parseError" class="parse-error">
|
||||
Error: {{ store.parseError }}
|
||||
</div>
|
||||
<ParsedTree v-if="store.parseResult" :fields="store.parseResult.fields" />
|
||||
<div v-else-if="!store.parseError" class="empty-hint">
|
||||
Define a schema and hex dump, then select <strong>Parse</strong>.
|
||||
</div>
|
||||
</aside>
|
||||
</main>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { onMounted } from 'vue'
|
||||
import { useParserStore } from '@/stores/parser'
|
||||
import PanelHeader from '@/components/PanelHeader.vue'
|
||||
import SchemaEditor from '@/components/SchemaEditor.vue'
|
||||
import HexInput from '@/components/HexInput.vue'
|
||||
import HexViewer from '@/components/HexViewer.vue'
|
||||
import ParsedTree from '@/components/ParsedTree.vue'
|
||||
|
||||
const store = useParserStore()
|
||||
|
||||
onMounted(async () => {
|
||||
await store.initWasm()
|
||||
store.runParse()
|
||||
})
|
||||
</script>
|
||||
@@ -0,0 +1,16 @@
|
||||
<template>
|
||||
<div class="hex-input-wrapper">
|
||||
<textarea
|
||||
v-model="store.hexInput"
|
||||
class="hex-input"
|
||||
spellcheck="false"
|
||||
placeholder="Paste hex dump here…"
|
||||
rows="4"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { useParserStore } from '@/stores/parser'
|
||||
const store = useParserStore()
|
||||
</script>
|
||||
@@ -0,0 +1,130 @@
|
||||
<template>
|
||||
<div class="hex-viewer" ref="viewerEl">
|
||||
<div class="hex-grid">
|
||||
<!-- Row labels + hex + ascii -->
|
||||
<template v-for="(row, ri) in rows" :key="ri">
|
||||
<!-- Offset -->
|
||||
<span class="hex-offset">{{ row.offset.toString(16).padStart(4, '0') }}</span>
|
||||
|
||||
<!-- Hex bytes -->
|
||||
<span class="hex-bytes">
|
||||
<span
|
||||
v-for="(byte, ci) in row.bytes"
|
||||
:key="ci"
|
||||
class="hex-byte"
|
||||
:class="byteClass(row.offset + ci)"
|
||||
@mouseenter="onHoverByte(row.offset + ci)"
|
||||
@mouseleave="onLeave"
|
||||
@click="onClickByte(row.offset + ci)"
|
||||
>{{ byte.toString(16).padStart(2, '0') }}</span>
|
||||
<!-- Padding for last row -->
|
||||
<span
|
||||
v-for="p in (16 - row.bytes.length)"
|
||||
:key="'p' + p"
|
||||
class="hex-byte hex-pad"
|
||||
> </span>
|
||||
</span>
|
||||
|
||||
<!-- ASCII -->
|
||||
<span class="hex-ascii">
|
||||
<span
|
||||
v-for="(byte, ci) in row.bytes"
|
||||
:key="ci"
|
||||
class="ascii-char"
|
||||
:class="byteClass(row.offset + ci)"
|
||||
@mouseenter="onHoverByte(row.offset + ci)"
|
||||
@mouseleave="onLeave"
|
||||
>{{ toAscii(byte) }}</span>
|
||||
</span>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<!-- Legend -->
|
||||
<div v-if="store.selectedField" class="hex-legend">
|
||||
<span class="legend-dot selected" /> Selected:
|
||||
<strong>{{ store.selectedField.name }}</strong>
|
||||
offset {{ store.selectedField.offset }}, {{ store.selectedField.size }}B
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue'
|
||||
import { useParserStore } from '@/stores/parser'
|
||||
import type { ParsedField } from '@/types/parser'
|
||||
|
||||
const store = useParserStore()
|
||||
const viewerEl = ref<HTMLElement | null>(null)
|
||||
|
||||
const BYTES_PER_ROW = 16
|
||||
|
||||
interface Row { offset: number; bytes: number[] }
|
||||
|
||||
const rows = computed<Row[]>(() => {
|
||||
const bs = store.bytes
|
||||
const out: Row[] = []
|
||||
for (let i = 0; i < bs.length; i += BYTES_PER_ROW) {
|
||||
out.push({ offset: i, bytes: bs.slice(i, i + BYTES_PER_ROW) })
|
||||
}
|
||||
return out
|
||||
})
|
||||
|
||||
/** Flatten all fields (incl. children) for range lookups */
|
||||
const allFields = computed<ParsedField[]>(() => {
|
||||
if (!store.parseResult) return []
|
||||
return flatten(store.parseResult.fields)
|
||||
})
|
||||
|
||||
function flatten(fields: ParsedField[]): ParsedField[] {
|
||||
return fields.flatMap(f => [f, ...(f.children ? flatten(f.children) : [])])
|
||||
}
|
||||
|
||||
/** Return the field containing byte index `i` */
|
||||
function fieldAt(i: number): ParsedField | undefined {
|
||||
return allFields.value.find(f => i >= f.offset && i < f.offset + f.size)
|
||||
}
|
||||
|
||||
function byteClass(i: number) {
|
||||
const hovered = store.hoveredRange
|
||||
const selected = store.selectedField
|
||||
|
||||
const classes: string[] = []
|
||||
|
||||
if (selected && i >= selected.offset && i < selected.offset + selected.size) {
|
||||
classes.push('byte-selected')
|
||||
}
|
||||
|
||||
if (hovered && i >= hovered[0] && i < hovered[1]) {
|
||||
classes.push('byte-hovered')
|
||||
}
|
||||
|
||||
const field = fieldAt(i)
|
||||
if (field) {
|
||||
classes.push('byte-parsed')
|
||||
if (field.checksum_valid === false) classes.push('byte-error')
|
||||
else if (field.checksum_valid === true) classes.push('byte-ok')
|
||||
}
|
||||
|
||||
return classes
|
||||
}
|
||||
|
||||
function onHoverByte(i: number) {
|
||||
const f = fieldAt(i)
|
||||
if (f) store.setHovered([f.offset, f.offset + f.size])
|
||||
else store.setHovered(null)
|
||||
}
|
||||
|
||||
function onLeave() {
|
||||
store.setHovered(null)
|
||||
}
|
||||
|
||||
function onClickByte(i: number) {
|
||||
const f = fieldAt(i)
|
||||
store.setSelected(f ?? null)
|
||||
}
|
||||
|
||||
function toAscii(b: number): string {
|
||||
if (b >= 0x20 && b < 0x7f) return String.fromCharCode(b)
|
||||
return '·'
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,10 @@
|
||||
<template>
|
||||
<div class="panel-header">
|
||||
<span class="panel-title">{{ title }}</span>
|
||||
<slot />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
defineProps<{ title: string }>()
|
||||
</script>
|
||||
@@ -0,0 +1,128 @@
|
||||
<template>
|
||||
<div
|
||||
class="parsed-node"
|
||||
:class="{
|
||||
'node-selected': isSelected,
|
||||
'node-hovered': isHovered,
|
||||
'node-error': field.checksum_valid === false,
|
||||
'node-ok': field.checksum_valid === true,
|
||||
}"
|
||||
:style="{ paddingLeft: depth * 16 + 8 + 'px' }"
|
||||
@mouseenter="onHover"
|
||||
@mouseleave="onLeave"
|
||||
@click.stop="onClick"
|
||||
>
|
||||
<button
|
||||
v-if="hasChildren"
|
||||
class="expand-btn"
|
||||
:aria-expanded="expanded"
|
||||
@click.stop="expanded = !expanded"
|
||||
>
|
||||
<span class="expand-icon" :class="{ expanded }" />
|
||||
</button>
|
||||
<span v-else class="expand-spacer" />
|
||||
|
||||
<span class="node-kind">{{ kindLabel }}</span>
|
||||
<span class="node-name">{{ field.name }}</span>
|
||||
|
||||
<span class="node-value">
|
||||
<template v-if="Array.isArray(field.value)">
|
||||
<template v-if="isFlagArray(field.value)">
|
||||
<span
|
||||
v-for="flag in (field.value as FlagValue[])"
|
||||
:key="flag.bit"
|
||||
class="flag-chip"
|
||||
:class="flag.set ? 'flag-set' : 'flag-unset'"
|
||||
>{{ flag.name }}</span>
|
||||
</template>
|
||||
<template v-else>
|
||||
<span class="bytes-preview">
|
||||
{{ (field.value as number[]).map(b => b.toString(16).padStart(2, '0')).join(' ') }}
|
||||
</span>
|
||||
</template>
|
||||
</template>
|
||||
<template v-else-if="field.value !== null">
|
||||
<span :class="valueClass">{{ displayValue }}</span>
|
||||
</template>
|
||||
</span>
|
||||
|
||||
<span class="node-meta">+{{ field.offset }} / {{ field.size }}B</span>
|
||||
|
||||
<span v-if="field.checksum_valid === true" class="badge badge-ok">VALID</span>
|
||||
<span v-else-if="field.checksum_valid === false" class="badge badge-err">INVALID</span>
|
||||
</div>
|
||||
|
||||
<div v-if="field.description && isSelected" class="node-desc" :style="{ paddingLeft: depth * 16 + 36 + 'px' }">
|
||||
{{ field.description }}
|
||||
</div>
|
||||
|
||||
<template v-if="hasChildren && expanded">
|
||||
<ParsedNode
|
||||
v-for="child in field.children"
|
||||
:key="child.name + child.offset"
|
||||
:field="child"
|
||||
:depth="depth + 1"
|
||||
/>
|
||||
</template>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, computed } from 'vue'
|
||||
import { useParserStore } from '@/stores/parser'
|
||||
import type { ParsedField, FlagValue } from '@/types/parser'
|
||||
|
||||
const props = defineProps<{ field: ParsedField; depth: number }>()
|
||||
const store = useParserStore()
|
||||
const expanded = ref(true)
|
||||
|
||||
const hasChildren = computed(() => !!props.field.children?.length)
|
||||
|
||||
const isSelected = computed(() =>
|
||||
store.selectedField?.offset === props.field.offset &&
|
||||
store.selectedField?.name === props.field.name
|
||||
)
|
||||
|
||||
const isHovered = computed(() => {
|
||||
const h = store.hoveredRange
|
||||
if (!h) return false
|
||||
return props.field.offset >= h[0] && props.field.offset < h[1]
|
||||
})
|
||||
|
||||
const kindLabel = computed(() =>
|
||||
props.field.kind.replace(/([A-Z])/g, ' $1').trim()
|
||||
)
|
||||
|
||||
const displayValue = computed(() => {
|
||||
const v = props.field.value
|
||||
if (typeof v === 'number') {
|
||||
if (props.field.kind.toLowerCase().includes('float')) return v.toFixed(6)
|
||||
return `${v} (0x${v.toString(16).toUpperCase()})`
|
||||
}
|
||||
return String(v)
|
||||
})
|
||||
|
||||
const valueClass = computed(() => {
|
||||
const k = props.field.kind.toLowerCase()
|
||||
if (k.includes('uint') || k.includes('int')) return 'val-int'
|
||||
if (k.includes('float')) return 'val-float'
|
||||
if (k.includes('string')) return 'val-string'
|
||||
if (k.includes('crc')) return 'val-crc'
|
||||
return ''
|
||||
})
|
||||
|
||||
function isFlagArray(v: unknown[]): v is FlagValue[] {
|
||||
return v.length > 0 && typeof (v[0] as FlagValue).bit === 'number'
|
||||
}
|
||||
|
||||
function onHover() {
|
||||
store.setHovered([props.field.offset, props.field.offset + props.field.size])
|
||||
}
|
||||
|
||||
function onLeave() {
|
||||
store.setHovered(null)
|
||||
}
|
||||
|
||||
function onClick() {
|
||||
store.setSelected(isSelected.value ? null : props.field)
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,17 @@
|
||||
<template>
|
||||
<div class="parsed-tree">
|
||||
<ParsedNode
|
||||
v-for="field in fields"
|
||||
:key="field.name + field.offset"
|
||||
:field="field"
|
||||
:depth="0"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import type { ParsedField } from '@/types/parser'
|
||||
import ParsedNode from './ParsedNode.vue'
|
||||
|
||||
defineProps<{ fields: ParsedField[] }>()
|
||||
</script>
|
||||
@@ -0,0 +1,48 @@
|
||||
<template>
|
||||
<div class="schema-editor">
|
||||
<textarea
|
||||
v-model="store.schemaText"
|
||||
class="schema-textarea"
|
||||
spellcheck="false"
|
||||
autocomplete="off"
|
||||
@keydown.tab.prevent="onTab"
|
||||
@input="onInput"
|
||||
/>
|
||||
<div v-if="schemaError" class="schema-error">Error: {{ schemaError }}</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, watch } from 'vue'
|
||||
import { useParserStore } from '@/stores/parser'
|
||||
import { validateJsonSchema } from '@/utils/schema'
|
||||
|
||||
const store = useParserStore()
|
||||
const schemaError = ref<string | null>(null)
|
||||
|
||||
function validate() {
|
||||
if (store.schemaFormat === 'json') {
|
||||
schemaError.value = validateJsonSchema(store.schemaText)
|
||||
} else {
|
||||
schemaError.value = null
|
||||
}
|
||||
}
|
||||
|
||||
function onInput() {
|
||||
validate()
|
||||
}
|
||||
|
||||
function onTab(e: KeyboardEvent) {
|
||||
const el = e.target as HTMLTextAreaElement
|
||||
const start = el.selectionStart
|
||||
const end = el.selectionEnd
|
||||
store.schemaText =
|
||||
store.schemaText.substring(0, start) + ' ' + store.schemaText.substring(end)
|
||||
// Move cursor
|
||||
setTimeout(() => {
|
||||
el.selectionStart = el.selectionEnd = start + 2
|
||||
})
|
||||
}
|
||||
|
||||
watch(() => store.schemaFormat, validate)
|
||||
</script>
|
||||
@@ -0,0 +1,51 @@
|
||||
{
|
||||
"name": "Example Frame",
|
||||
"endian": "big",
|
||||
"fields": [
|
||||
{
|
||||
"name": "magic",
|
||||
"type": "uint8",
|
||||
"description": "Protocol magic byte (0xFF)"
|
||||
},
|
||||
{
|
||||
"name": "payload_len",
|
||||
"type": "uint8",
|
||||
"description": "Length of payload string"
|
||||
},
|
||||
{
|
||||
"name": "payload",
|
||||
"type": "string_fixed",
|
||||
"length": 5,
|
||||
"description": "Fixed-length ASCII payload"
|
||||
},
|
||||
{
|
||||
"name": "raw_data",
|
||||
"type": "bytes",
|
||||
"length": 4,
|
||||
"description": "Raw 4-byte data blob"
|
||||
},
|
||||
{
|
||||
"name": "tag",
|
||||
"type": "string_fixed",
|
||||
"length": 4,
|
||||
"description": "ASCII tag (ABCD)"
|
||||
},
|
||||
{
|
||||
"name": "checksum",
|
||||
"type": "crc32",
|
||||
"checksum_range": [0, 11],
|
||||
"description": "CRC-32 over bytes 0-10"
|
||||
},
|
||||
{
|
||||
"name": "flags",
|
||||
"type": "bitflags16",
|
||||
"description": "Status flags",
|
||||
"flags": [
|
||||
{ "bit": 0, "name": "ACK", "description": "Acknowledge" },
|
||||
{ "bit": 1, "name": "SYN", "description": "Synchronise" },
|
||||
{ "bit": 2, "name": "FIN", "description": "Finished" },
|
||||
{ "bit": 7, "name": "ERR", "description": "Error" }
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
export const EXAMPLE_SCHEMA = JSON.stringify(
|
||||
{
|
||||
name: 'Example Frame',
|
||||
endian: 'big',
|
||||
fields: [
|
||||
{
|
||||
name: 'magic',
|
||||
type: 'uint8',
|
||||
description: 'Protocol magic byte (0xFF)',
|
||||
},
|
||||
{
|
||||
name: 'payload_len',
|
||||
type: 'uint8',
|
||||
description: 'Length of payload string',
|
||||
},
|
||||
{
|
||||
name: 'payload',
|
||||
type: 'string_fixed',
|
||||
length: 5,
|
||||
description: 'Fixed-length ASCII payload',
|
||||
},
|
||||
{
|
||||
name: 'raw_data',
|
||||
type: 'bytes',
|
||||
length: 4,
|
||||
description: 'Raw 4-byte data blob',
|
||||
},
|
||||
{
|
||||
name: 'tag',
|
||||
type: 'string_fixed',
|
||||
length: 4,
|
||||
description: 'ASCII tag (ABCD)',
|
||||
},
|
||||
{
|
||||
name: 'checksum',
|
||||
type: 'crc32',
|
||||
checksum_range: [0, 11],
|
||||
description: 'CRC-32 over bytes 0-10',
|
||||
},
|
||||
{
|
||||
name: 'flags',
|
||||
type: 'bitflags16',
|
||||
description: 'Status flags',
|
||||
flags: [
|
||||
{ bit: 0, name: 'ACK', description: 'Acknowledge' },
|
||||
{ bit: 1, name: 'SYN', description: 'Synchronise' },
|
||||
{ bit: 2, name: 'FIN', description: 'Finished' },
|
||||
{ bit: 7, name: 'ERR', description: 'Error' },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)
|
||||
|
||||
/** Example frame with valid CRC-32 (ISO HDLC) over bytes 0-10 and flags ACK|SYN. */
|
||||
export const EXAMPLE_HEX = [
|
||||
'FF 05 48 65 6C 6C 6F',
|
||||
'00 01 02 03',
|
||||
'41 42 43 44',
|
||||
'E8 6B B6 E1',
|
||||
'00 03',
|
||||
].join('\n')
|
||||
@@ -0,0 +1,8 @@
|
||||
import { createApp } from 'vue'
|
||||
import { createPinia } from 'pinia'
|
||||
import App from './App.vue'
|
||||
import './styles/main.css'
|
||||
|
||||
const app = createApp(App)
|
||||
app.use(createPinia())
|
||||
app.mount('#app')
|
||||
@@ -0,0 +1,62 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import { useParserStore } from '@/stores/parser'
|
||||
import { EXAMPLE_HEX } from '@/fixtures/example'
|
||||
import type { ParseResult } from '@/types/parser'
|
||||
|
||||
describe('useParserStore', () => {
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia())
|
||||
})
|
||||
|
||||
it('derives bytes from hex input', () => {
|
||||
const store = useParserStore()
|
||||
store.hexInput = 'FF 00 AB'
|
||||
expect(store.bytes).toEqual([0xFF, 0x00, 0xAB])
|
||||
})
|
||||
|
||||
it('loads example fixture with valid byte length', () => {
|
||||
const store = useParserStore()
|
||||
store.hexInput = EXAMPLE_HEX
|
||||
expect(store.bytes.length).toBe(21)
|
||||
})
|
||||
|
||||
it('reports parse error when WASM is unavailable', () => {
|
||||
const store = useParserStore()
|
||||
store.runParse()
|
||||
expect(store.parseError).toBe('WASM module not ready.')
|
||||
})
|
||||
|
||||
it('stores parse result from WASM module', () => {
|
||||
const store = useParserStore()
|
||||
const result: ParseResult = {
|
||||
fields: [],
|
||||
total_bytes: 4,
|
||||
consumed_bytes: 4,
|
||||
}
|
||||
|
||||
store.wasmReady = true
|
||||
store.wasm = {
|
||||
parse: vi.fn().mockReturnValue(result),
|
||||
hex_to_bytes_js: vi.fn(),
|
||||
}
|
||||
|
||||
store.runParse()
|
||||
expect(store.parseResult).toEqual(result)
|
||||
expect(store.parseError).toBeNull()
|
||||
})
|
||||
|
||||
it('captures invalid JSON schema errors', () => {
|
||||
const store = useParserStore()
|
||||
store.wasmReady = true
|
||||
store.wasm = {
|
||||
parse: vi.fn(),
|
||||
hex_to_bytes_js: vi.fn(),
|
||||
}
|
||||
store.schemaText = '{bad json'
|
||||
|
||||
store.runParse()
|
||||
expect(store.parseError).toMatch(/JSON schema error/)
|
||||
expect(store.parseResult).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,100 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref, computed, shallowRef } from 'vue'
|
||||
import type { ParseResult, ParsedField } from '@/types/parser'
|
||||
import { parseHexInput } from '@/utils/hex'
|
||||
import { validateJsonSchema } from '@/utils/schema'
|
||||
import { EXAMPLE_HEX, EXAMPLE_SCHEMA } from '@/fixtures/example'
|
||||
|
||||
interface WasmModule {
|
||||
parse: (hex: string, schema: string) => ParseResult
|
||||
hex_to_bytes_js: (hex: string) => Uint8Array
|
||||
}
|
||||
|
||||
export const useParserStore = defineStore('parser', () => {
|
||||
// ── State ──────────────────────────────────────────────────────────────
|
||||
const wasm = shallowRef<WasmModule | null>(null)
|
||||
const wasmReady = ref(false)
|
||||
const wasmError = ref<string | null>(null)
|
||||
|
||||
const hexInput = ref<string>(EXAMPLE_HEX)
|
||||
const schemaText = ref<string>(EXAMPLE_SCHEMA)
|
||||
const schemaFormat = ref<'json' | 'yaml'>('json')
|
||||
|
||||
const parseResult = ref<ParseResult | null>(null)
|
||||
const parseError = ref<string | null>(null)
|
||||
|
||||
// Highlighted byte range [start, end) for hover sync.
|
||||
const hoveredRange = ref<[number, number] | null>(null)
|
||||
// Clicked / selected field for persistent highlight.
|
||||
const selectedField = ref<ParsedField | null>(null)
|
||||
|
||||
// ── WASM init ──────────────────────────────────────────────────────────
|
||||
async function initWasm() {
|
||||
try {
|
||||
// Dynamic import — wasm-pack output directory resolved at build time.
|
||||
const mod = await import('../wasm/hex_pigeon_parser.js')
|
||||
await mod.default() // run wasm-bindgen init
|
||||
wasm.value = mod as unknown as WasmModule
|
||||
wasmReady.value = true
|
||||
} catch (e) {
|
||||
wasmError.value = `Failed to load WASM: ${e}`
|
||||
}
|
||||
}
|
||||
|
||||
// ── Actions ────────────────────────────────────────────────────────────
|
||||
function runParse() {
|
||||
parseError.value = null
|
||||
parseResult.value = null
|
||||
|
||||
if (!wasmReady.value || !wasm.value) {
|
||||
parseError.value = 'WASM module not ready.'
|
||||
return
|
||||
}
|
||||
|
||||
let schemaJson = schemaText.value
|
||||
if (schemaFormat.value === 'yaml') {
|
||||
try {
|
||||
// @ts-ignore – dynamic import resolved at runtime
|
||||
const yaml = (window as any).__yaml
|
||||
schemaJson = JSON.stringify(yaml.load(schemaText.value))
|
||||
} catch (e) {
|
||||
parseError.value = `YAML parse error: ${e}`
|
||||
return
|
||||
}
|
||||
} else {
|
||||
const err = validateJsonSchema(schemaJson)
|
||||
if (err) {
|
||||
parseError.value = `JSON schema error: ${err}`
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const result = wasm.value.parse(hexInput.value, schemaJson)
|
||||
parseResult.value = result
|
||||
} catch (e) {
|
||||
parseError.value = String(e)
|
||||
}
|
||||
}
|
||||
|
||||
const bytes = computed<number[]>(() => parseHexInput(hexInput.value))
|
||||
|
||||
function setHovered(range: [number, number] | null) {
|
||||
hoveredRange.value = range
|
||||
}
|
||||
|
||||
function setSelected(field: ParsedField | null) {
|
||||
selectedField.value = field
|
||||
}
|
||||
|
||||
return {
|
||||
wasm, wasmReady, wasmError,
|
||||
hexInput, schemaText, schemaFormat,
|
||||
parseResult, parseError,
|
||||
hoveredRange, selectedField,
|
||||
bytes,
|
||||
initWasm, runParse, setHovered, setSelected,
|
||||
}
|
||||
})
|
||||
|
||||
export { EXAMPLE_HEX, EXAMPLE_SCHEMA }
|
||||
@@ -0,0 +1,227 @@
|
||||
/* ── Reset & tokens ────────────────────────────────────────────────────── */
|
||||
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
|
||||
:root {
|
||||
--bg0: #0d1117;
|
||||
--bg1: #161b22;
|
||||
--bg2: #21262d;
|
||||
--bg3: #30363d;
|
||||
--border: #30363d;
|
||||
--text: #e6edf3;
|
||||
--text-muted: #7d8590;
|
||||
--accent: #58a6ff;
|
||||
--accent2: #3fb950;
|
||||
--warn: #f85149;
|
||||
--yellow: #e3b341;
|
||||
--purple: #bc8cff;
|
||||
--orange: #ffa657;
|
||||
|
||||
--font-mono: 'JetBrains Mono', 'Fira Code', 'Cascadia Code', 'Consolas', monospace;
|
||||
--font-ui: system-ui, -apple-system, 'Segoe UI', sans-serif;
|
||||
--radius: 6px;
|
||||
}
|
||||
|
||||
html, body { height: 100%; background: var(--bg0); color: var(--text); font-family: var(--font-ui); font-size: 14px; }
|
||||
|
||||
/* ── App shell ──────────────────────────────────────────────────────────── */
|
||||
.app { display: flex; flex-direction: column; height: 100vh; overflow: hidden; }
|
||||
|
||||
/* ── Header ────────────────────────────────────────────────────────────── */
|
||||
.app-header {
|
||||
display: flex; align-items: center; justify-content: space-between;
|
||||
padding: 10px 16px;
|
||||
background: var(--bg1);
|
||||
border-bottom: 1px solid var(--border);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.brand { display: flex; align-items: baseline; gap: 12px; }
|
||||
.logo {
|
||||
font-size: 1rem;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.12em;
|
||||
text-transform: uppercase;
|
||||
color: var(--text);
|
||||
}
|
||||
.subtitle { color: var(--text-muted); font-size: 0.82rem; }
|
||||
.header-actions { display: flex; gap: 8px; }
|
||||
|
||||
/* ── Buttons ────────────────────────────────────────────────────────────── */
|
||||
.btn { padding: 6px 16px; border-radius: var(--radius); border: none; cursor: pointer; font-weight: 600; transition: opacity 0.15s; }
|
||||
.btn:disabled { opacity: 0.4; cursor: not-allowed; }
|
||||
.btn-primary { background: var(--bg3); color: var(--text); border: 1px solid var(--border); }
|
||||
.btn-primary:not(:disabled):hover { border-color: var(--accent); color: var(--accent); }
|
||||
|
||||
/* ── Banners ────────────────────────────────────────────────────────────── */
|
||||
.banner { padding: 8px 16px; font-size: 0.85rem; }
|
||||
.banner-error { background: #2d1a1a; color: var(--warn); border-bottom: 1px solid var(--warn); }
|
||||
.banner code { background: rgba(255,255,255,0.08); padding: 0 4px; border-radius: 3px; }
|
||||
|
||||
/* ── Panels ─────────────────────────────────────────────────────────────── */
|
||||
.panels { display: grid; grid-template-columns: 320px 1fr 340px; flex: 1; overflow: hidden; }
|
||||
|
||||
.panel { display: flex; flex-direction: column; overflow: hidden; border-right: 1px solid var(--border); }
|
||||
.panel:last-child { border-right: none; }
|
||||
|
||||
.panel-header {
|
||||
display: flex; align-items: center; justify-content: space-between;
|
||||
padding: 6px 12px;
|
||||
background: var(--bg2);
|
||||
border-bottom: 1px solid var(--border);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.panel-title {
|
||||
font-weight: 600;
|
||||
font-size: 0.72rem;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
.byte-count { font-family: var(--font-mono); font-size: 0.78rem; color: var(--text-muted); }
|
||||
|
||||
.format-select {
|
||||
background: var(--bg3); color: var(--text); border: 1px solid var(--border);
|
||||
border-radius: var(--radius); padding: 2px 6px; font-size: 0.8rem;
|
||||
}
|
||||
|
||||
/* ── Schema editor ───────────────────────────────────────────────────────── */
|
||||
.schema-editor { display: flex; flex-direction: column; flex: 1; overflow: hidden; }
|
||||
.schema-textarea {
|
||||
flex: 1; resize: none; font-family: var(--font-mono); font-size: 0.8rem;
|
||||
background: var(--bg1); color: var(--text); border: none; outline: none;
|
||||
padding: 12px; line-height: 1.6; tab-size: 2;
|
||||
}
|
||||
.schema-error { padding: 6px 12px; background: #2d1a1a; color: var(--warn); font-size: 0.8rem; flex-shrink: 0; }
|
||||
|
||||
/* ── Hex input ───────────────────────────────────────────────────────────── */
|
||||
.hex-input-wrapper { flex-shrink: 0; border-bottom: 1px solid var(--border); }
|
||||
.hex-input {
|
||||
width: 100%; resize: none; font-family: var(--font-mono); font-size: 0.85rem;
|
||||
background: var(--bg2); color: var(--accent); border: none; outline: none;
|
||||
padding: 10px 12px; line-height: 1.7;
|
||||
}
|
||||
|
||||
/* ── Hex viewer ──────────────────────────────────────────────────────────── */
|
||||
.hex-viewer { flex: 1; overflow-y: auto; padding: 8px 0; }
|
||||
|
||||
.hex-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 50px 1fr auto;
|
||||
gap: 0;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 0.8rem;
|
||||
line-height: 1.9;
|
||||
}
|
||||
|
||||
.hex-offset { color: var(--text-muted); padding: 0 8px; user-select: none; }
|
||||
|
||||
.hex-bytes { display: flex; flex-wrap: wrap; gap: 2px; padding: 0 4px; }
|
||||
|
||||
.hex-byte {
|
||||
display: inline-block;
|
||||
width: 22px; text-align: center;
|
||||
cursor: pointer;
|
||||
border-radius: 3px;
|
||||
transition: background 0.08s;
|
||||
padding: 0 1px;
|
||||
}
|
||||
.hex-pad { color: transparent; }
|
||||
|
||||
.hex-ascii { color: var(--text-muted); padding: 0 8px; user-select: none; letter-spacing: 0.05em; }
|
||||
.ascii-char { cursor: pointer; border-radius: 2px; }
|
||||
|
||||
/* ── Byte states ─────────────────────────────────────────────────────────── */
|
||||
.byte-parsed { color: var(--text); }
|
||||
.byte-hovered { background: rgba(88,166,255,0.25); color: #fff; }
|
||||
.byte-selected { background: var(--accent); color: #000 !important; border-radius: 3px; }
|
||||
.byte-error { color: var(--warn); }
|
||||
.byte-ok { color: var(--accent2); }
|
||||
|
||||
/* ── Hex legend ─────────────────────────────────────────────────────────── */
|
||||
.hex-legend {
|
||||
display: flex; align-items: center; gap: 6px;
|
||||
padding: 6px 12px; font-size: 0.78rem; color: var(--text-muted);
|
||||
border-top: 1px solid var(--border); flex-shrink: 0;
|
||||
}
|
||||
.legend-dot { display: inline-block; width: 10px; height: 10px; border-radius: 2px; }
|
||||
.legend-dot.selected { background: var(--accent); }
|
||||
|
||||
/* ── Parsed tree ────────────────────────────────────────────────────────── */
|
||||
.parsed-tree { flex: 1; overflow-y: auto; }
|
||||
|
||||
.parsed-node {
|
||||
display: flex; align-items: center; gap: 6px;
|
||||
padding: 3px 8px; cursor: pointer;
|
||||
border-left: 2px solid transparent;
|
||||
transition: background 0.08s;
|
||||
font-size: 0.82rem;
|
||||
}
|
||||
.parsed-node:hover { background: var(--bg2); }
|
||||
.node-selected { background: rgba(88,166,255,0.12) !important; border-left-color: var(--accent); }
|
||||
.node-hovered { background: rgba(88,166,255,0.07); }
|
||||
.node-error { border-left-color: var(--warn); }
|
||||
.node-ok { border-left-color: var(--accent2); }
|
||||
|
||||
.expand-btn {
|
||||
background: none; border: none; cursor: pointer;
|
||||
width: 14px; height: 14px; flex-shrink: 0;
|
||||
display: inline-flex; align-items: center; justify-content: center;
|
||||
}
|
||||
.expand-icon {
|
||||
display: block;
|
||||
width: 0; height: 0;
|
||||
border-top: 4px solid transparent;
|
||||
border-bottom: 4px solid transparent;
|
||||
border-left: 6px solid var(--text-muted);
|
||||
transition: transform 0.12s ease;
|
||||
}
|
||||
.expand-icon.expanded { transform: rotate(90deg); }
|
||||
.expand-spacer { display: inline-block; width: 14px; }
|
||||
|
||||
.node-kind {
|
||||
font-size: 0.68rem; font-family: var(--font-mono);
|
||||
background: var(--bg3); color: var(--purple);
|
||||
border-radius: 3px; padding: 1px 5px;
|
||||
white-space: nowrap; flex-shrink: 0;
|
||||
}
|
||||
|
||||
.node-name { font-weight: 600; color: var(--text); flex-shrink: 0; }
|
||||
|
||||
.node-value { flex: 1; font-family: var(--font-mono); font-size: 0.78rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
|
||||
.node-meta { color: var(--text-muted); font-family: var(--font-mono); font-size: 0.7rem; flex-shrink: 0; }
|
||||
|
||||
.val-int { color: var(--orange); }
|
||||
.val-float { color: var(--yellow); }
|
||||
.val-string { color: var(--accent2); }
|
||||
.val-crc { color: var(--purple); }
|
||||
|
||||
.node-desc {
|
||||
font-size: 0.78rem; color: var(--text-muted);
|
||||
padding: 2px 8px 4px;
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
/* ── Flag chips ─────────────────────────────────────────────────────────── */
|
||||
.flag-chip {
|
||||
display: inline-block; font-size: 0.65rem; font-family: var(--font-mono);
|
||||
padding: 1px 5px; border-radius: 3px; margin-right: 3px; font-weight: 700;
|
||||
}
|
||||
.flag-set { background: rgba(63,185,80,0.25); color: var(--accent2); }
|
||||
.flag-unset { background: var(--bg3); color: var(--text-muted); }
|
||||
|
||||
.bytes-preview { color: var(--accent); font-size: 0.72rem; }
|
||||
|
||||
/* ── Badges ─────────────────────────────────────────────────────────────── */
|
||||
.badge { font-size: 0.65rem; font-weight: 700; padding: 1px 6px; border-radius: 10px; flex-shrink: 0; }
|
||||
.badge-ok { background: rgba(63,185,80,0.2); color: var(--accent2); }
|
||||
.badge-err { background: rgba(248,81,73,0.2); color: var(--warn); }
|
||||
|
||||
/* ── Empty hints ────────────────────────────────────────────────────────── */
|
||||
.empty-hint { padding: 24px 16px; color: var(--text-muted); text-align: center; }
|
||||
.parse-error { padding: 10px 14px; background: #2d1a1a; color: var(--warn); font-size: 0.82rem; border-bottom: 1px solid var(--warn); }
|
||||
|
||||
/* ── Scrollbars ─────────────────────────────────────────────────────────── */
|
||||
::-webkit-scrollbar { width: 6px; height: 6px; }
|
||||
::-webkit-scrollbar-track { background: var(--bg0); }
|
||||
::-webkit-scrollbar-thumb { background: var(--bg3); border-radius: 3px; }
|
||||
::-webkit-scrollbar-thumb:hover { background: var(--text-muted); }
|
||||
@@ -0,0 +1,70 @@
|
||||
// ── Schema types (mirrors Rust schema.rs) ──────────────────────────────────
|
||||
|
||||
export type Endian = 'big' | 'little'
|
||||
|
||||
export type FieldKind =
|
||||
| 'uint8' | 'uint16' | 'uint32' | 'uint64'
|
||||
| 'int8' | 'int16' | 'int32'
|
||||
| 'float32' | 'float64'
|
||||
| 'bitflags8' | 'bitflags16'
|
||||
| 'bytes' | 'string_fixed' | 'string_lp8' | 'string_lp16'
|
||||
| 'crc16' | 'crc32'
|
||||
| 'repeated' | 'padding'
|
||||
|
||||
export interface FlagDef {
|
||||
bit: number
|
||||
name: string
|
||||
description?: string
|
||||
}
|
||||
|
||||
export type CountSpec = number | string
|
||||
|
||||
export interface FieldDef {
|
||||
name: string
|
||||
type: FieldKind
|
||||
endian?: Endian
|
||||
description?: string
|
||||
flags?: FlagDef[]
|
||||
length?: number
|
||||
checksum_range?: [number, number]
|
||||
count?: CountSpec
|
||||
fields?: FieldDef[]
|
||||
}
|
||||
|
||||
export interface Schema {
|
||||
name?: string
|
||||
endian?: Endian
|
||||
fields: FieldDef[]
|
||||
}
|
||||
|
||||
// ── ParseResult types (mirrors Rust parser.rs) ─────────────────────────────
|
||||
|
||||
export type ParsedValue =
|
||||
| number
|
||||
| string
|
||||
| number[] // bytes
|
||||
| FlagValue[]
|
||||
| null
|
||||
|
||||
export interface FlagValue {
|
||||
bit: number
|
||||
name: string
|
||||
set: boolean
|
||||
}
|
||||
|
||||
export interface ParsedField {
|
||||
name: string
|
||||
kind: string
|
||||
offset: number
|
||||
size: number
|
||||
value: ParsedValue
|
||||
description?: string
|
||||
children?: ParsedField[]
|
||||
checksum_valid?: boolean
|
||||
}
|
||||
|
||||
export interface ParseResult {
|
||||
fields: ParsedField[]
|
||||
total_bytes: number
|
||||
consumed_bytes: number
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseHexInput, formatHexBytes } from '@/utils/hex'
|
||||
|
||||
describe('parseHexInput', () => {
|
||||
it('parses spaced hex pairs', () => {
|
||||
expect(parseHexInput('FF 05 48 65')).toEqual([0xFF, 0x05, 0x48, 0x65])
|
||||
})
|
||||
|
||||
it('ignores newlines and tabs', () => {
|
||||
expect(parseHexInput('FF\n05\t48')).toEqual([0xFF, 0x05, 0x48])
|
||||
})
|
||||
|
||||
it('returns empty array for odd-length input', () => {
|
||||
expect(parseHexInput('ABC')).toEqual([])
|
||||
})
|
||||
|
||||
it('returns empty array for invalid digits', () => {
|
||||
expect(parseHexInput('GG')).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('formatHexBytes', () => {
|
||||
it('formats bytes as uppercase hex', () => {
|
||||
expect(formatHexBytes([0x0a, 0xff])).toBe('0A FF')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,17 @@
|
||||
/** Parse a hex dump string into byte values. Whitespace is ignored. */
|
||||
export function parseHexInput(hex: string): number[] {
|
||||
const clean = hex.replace(/\s/g, '')
|
||||
if (clean.length % 2 !== 0) return []
|
||||
const out: number[] = []
|
||||
for (let i = 0; i < clean.length; i += 2) {
|
||||
const b = parseInt(clean.slice(i, i + 2), 16)
|
||||
if (Number.isNaN(b)) return []
|
||||
out.push(b)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** Format bytes as uppercase hex pairs separated by spaces. */
|
||||
export function formatHexBytes(bytes: number[]): string {
|
||||
return bytes.map(b => b.toString(16).padStart(2, '0').toUpperCase()).join(' ')
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { validateJsonSchema } from '@/utils/schema'
|
||||
|
||||
describe('validateJsonSchema', () => {
|
||||
it('accepts valid JSON', () => {
|
||||
expect(validateJsonSchema('{"fields":[]}')).toBeNull()
|
||||
})
|
||||
|
||||
it('rejects invalid JSON', () => {
|
||||
const err = validateJsonSchema('{invalid')
|
||||
expect(err).not.toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,9 @@
|
||||
/** Validate JSON schema text. Returns an error message or null if valid. */
|
||||
export function validateJsonSchema(text: string): string | null {
|
||||
try {
|
||||
JSON.parse(text)
|
||||
return null
|
||||
} catch (e) {
|
||||
return String(e)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "ESNext",
|
||||
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||
"moduleResolution": "bundler",
|
||||
"strict": true,
|
||||
"jsx": "preserve",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"skipLibCheck": true,
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
}
|
||||
},
|
||||
"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"],
|
||||
"exclude": ["node_modules", "dist"]
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import vue from '@vitejs/plugin-vue'
|
||||
import wasm from 'vite-plugin-wasm'
|
||||
import topLevelAwait from 'vite-plugin-top-level-await'
|
||||
import { fileURLToPath, URL } from 'node:url'
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [vue(), wasm(), topLevelAwait()],
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': fileURLToPath(new URL('./src', import.meta.url)),
|
||||
},
|
||||
},
|
||||
server: {
|
||||
port: 5173,
|
||||
fs: { allow: ['..'] },
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,16 @@
|
||||
import { defineConfig } from 'vitest/config'
|
||||
import vue from '@vitejs/plugin-vue'
|
||||
import { fileURLToPath, URL } from 'node:url'
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [vue()],
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': fileURLToPath(new URL('./src', import.meta.url)),
|
||||
},
|
||||
},
|
||||
test: {
|
||||
environment: 'node',
|
||||
include: ['src/**/*.test.ts'],
|
||||
},
|
||||
})
|
||||
Generated
+263
@@ -0,0 +1,263 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "bumpalo"
|
||||
version = "3.20.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
|
||||
|
||||
[[package]]
|
||||
name = "cfg-if"
|
||||
version = "1.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
|
||||
|
||||
[[package]]
|
||||
name = "crc"
|
||||
version = "3.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5eb8a2a1cd12ab0d987a5d5e825195d372001a4094a0376319d5a0ad71c1ba0d"
|
||||
dependencies = [
|
||||
"crc-catalog",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crc-catalog"
|
||||
version = "2.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853"
|
||||
|
||||
[[package]]
|
||||
name = "futures-core"
|
||||
version = "0.3.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"
|
||||
|
||||
[[package]]
|
||||
name = "futures-task"
|
||||
version = "0.3.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"
|
||||
|
||||
[[package]]
|
||||
name = "futures-util"
|
||||
version = "0.3.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
|
||||
dependencies = [
|
||||
"futures-core",
|
||||
"futures-task",
|
||||
"pin-project-lite",
|
||||
"slab",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hex-pigeon-parser"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"crc",
|
||||
"serde",
|
||||
"serde-wasm-bindgen",
|
||||
"serde_json",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itoa"
|
||||
version = "1.0.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
|
||||
|
||||
[[package]]
|
||||
name = "js-sys"
|
||||
version = "0.3.104"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0e0c1080212aad755ea003d18543e8768dd432c48819efd73a7bf1e39b7a5a3a"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"futures-util",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
||||
|
||||
[[package]]
|
||||
name = "once_cell"
|
||||
version = "1.21.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
||||
|
||||
[[package]]
|
||||
name = "pin-project-lite"
|
||||
version = "0.2.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.107"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustversion"
|
||||
version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde-wasm-bindgen"
|
||||
version = "0.6.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8302e169f0eddcc139c70f139d19d6467353af16f9fce27e8c30158036a1e16b"
|
||||
dependencies = [
|
||||
"js-sys",
|
||||
"serde",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_core"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
|
||||
dependencies = [
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_derive"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_json"
|
||||
version = "1.0.151"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14"
|
||||
dependencies = [
|
||||
"itoa",
|
||||
"memchr",
|
||||
"serde",
|
||||
"serde_core",
|
||||
"zmij",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "slab"
|
||||
version = "0.4.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "2.0.119"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "3.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e6275cddf4610d1775e6d1fe9469b2e77d0f39fd98fb7450901b821e0c53649f"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.24"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen"
|
||||
version = "0.2.127"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1b70935747edd64d89de3efa29d73789b806c15798f8e7dca4d8ac356b50ce70"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"once_cell",
|
||||
"rustversion",
|
||||
"wasm-bindgen-macro",
|
||||
"wasm-bindgen-shared",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen-macro"
|
||||
version = "0.2.127"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "77775f8f3f7217702089053b94958f8f54061a3f663417df76e19cbdcca29bc1"
|
||||
dependencies = [
|
||||
"quote",
|
||||
"wasm-bindgen-macro-support",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen-macro-support"
|
||||
version = "0.2.127"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e11d33f857dc2fb11b8bc75aee111aa9cbeb12cd9f25efd3d4c2a3dd4e235284"
|
||||
dependencies = [
|
||||
"bumpalo",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
"wasm-bindgen-shared",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen-shared"
|
||||
version = "0.2.127"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7ef64dbcc55df09c7e5a46182d181c2cfa3e925f3da937ea764728b4bbb9dcbf"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zmij"
|
||||
version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
|
||||
@@ -0,0 +1,18 @@
|
||||
[package]
|
||||
name = "hex-pigeon-parser"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib", "rlib"]
|
||||
|
||||
[dependencies]
|
||||
wasm-bindgen = "0.2"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde-wasm-bindgen = "0.6"
|
||||
serde_json = "1.0"
|
||||
crc = "3.2"
|
||||
|
||||
[profile.release]
|
||||
opt-level = "s"
|
||||
lto = true
|
||||
@@ -0,0 +1,37 @@
|
||||
use crc::{Crc, CRC_16_IBM_SDLC, CRC_32_ISO_HDLC};
|
||||
|
||||
pub fn compute_crc16(data: &[u8]) -> u16 {
|
||||
let crc = Crc::<u16>::new(&CRC_16_IBM_SDLC);
|
||||
crc.checksum(data)
|
||||
}
|
||||
|
||||
pub fn compute_crc32(data: &[u8]) -> u32 {
|
||||
let crc = Crc::<u32>::new(&CRC_32_ISO_HDLC);
|
||||
crc.checksum(data)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn crc16_is_deterministic() {
|
||||
let a = compute_crc16(b"123456789");
|
||||
let b = compute_crc16(b"123456789");
|
||||
assert_eq!(a, b);
|
||||
assert_ne!(a, compute_crc16(b"123456788"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crc32_is_deterministic() {
|
||||
let a = compute_crc32(b"123456789");
|
||||
let b = compute_crc32(b"123456789");
|
||||
assert_eq!(a, b);
|
||||
assert_ne!(a, compute_crc32(b"123456788"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_input_has_known_crc32() {
|
||||
assert_eq!(compute_crc32(&[]), 0x0000_0000);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
mod parser;
|
||||
mod schema;
|
||||
pub mod checksum;
|
||||
|
||||
pub use parser::*;
|
||||
pub use schema::*;
|
||||
|
||||
/// Entry point: parse `hex_input` against `schema_json`.
|
||||
/// Returns a JSON string of `ParseResult`.
|
||||
#[wasm_bindgen]
|
||||
pub fn parse(hex_input: &str, schema_json: &str) -> Result<JsValue, JsValue> {
|
||||
let schema: schema::Schema = serde_json::from_str(schema_json)
|
||||
.map_err(|e| JsValue::from_str(&format!("Schema error: {e}")))?;
|
||||
|
||||
let bytes = hex_to_bytes(hex_input)
|
||||
.map_err(|e| JsValue::from_str(&e))?;
|
||||
|
||||
let result = parser::parse_fields(&bytes, &schema.fields)
|
||||
.map_err(|e| JsValue::from_str(&e))?;
|
||||
|
||||
serde_wasm_bindgen::to_value(&result).map_err(|e| JsValue::from_str(&e.to_string()))
|
||||
}
|
||||
|
||||
/// Convert hex string (with optional spaces/newlines) to bytes.
|
||||
#[wasm_bindgen]
|
||||
pub fn hex_to_bytes_js(hex: &str) -> Result<Vec<u8>, JsValue> {
|
||||
hex_to_bytes(hex).map_err(|e| JsValue::from_str(&e))
|
||||
}
|
||||
|
||||
pub fn hex_to_bytes(hex: &str) -> Result<Vec<u8>, String> {
|
||||
let clean: String = hex.chars().filter(|c| !c.is_whitespace()).collect();
|
||||
if clean.len() % 2 != 0 {
|
||||
return Err(format!("Hex string has odd length: {}", clean.len()));
|
||||
}
|
||||
(0..clean.len())
|
||||
.step_by(2)
|
||||
.map(|i| {
|
||||
u8::from_str_radix(&clean[i..i + 2], 16)
|
||||
.map_err(|_| format!("Invalid hex byte at position {i}: '{}'", &clean[i..i + 2]))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::hex_to_bytes;
|
||||
|
||||
#[test]
|
||||
fn hex_to_bytes_accepts_whitespace() {
|
||||
let bytes = hex_to_bytes("FF 05\n48 65").expect("parse hex");
|
||||
assert_eq!(bytes, vec![0xFF, 0x05, 0x48, 0x65]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hex_to_bytes_rejects_odd_length() {
|
||||
let err = hex_to_bytes("ABC").unwrap_err();
|
||||
assert!(err.contains("odd length"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hex_to_bytes_rejects_invalid_digits() {
|
||||
let err = hex_to_bytes("GG").unwrap_err();
|
||||
assert!(err.contains("Invalid hex byte"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,309 @@
|
||||
use std::collections::HashMap;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use crate::schema::{CountSpec, Endian, FieldDef, FieldKind};
|
||||
use crate::checksum::{compute_crc16, compute_crc32};
|
||||
|
||||
/// The result of parsing a full frame.
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct ParseResult {
|
||||
pub fields: Vec<ParsedField>,
|
||||
pub total_bytes: usize,
|
||||
pub consumed_bytes: usize,
|
||||
}
|
||||
|
||||
/// A parsed field with its byte span for highlighting.
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct ParsedField {
|
||||
pub name: String,
|
||||
pub kind: String,
|
||||
/// Byte offset where this field starts.
|
||||
pub offset: usize,
|
||||
/// Number of bytes consumed.
|
||||
pub size: usize,
|
||||
/// Human-readable value.
|
||||
pub value: ParsedValue,
|
||||
pub description: Option<String>,
|
||||
/// For repeated/compound fields.
|
||||
pub children: Option<Vec<ParsedField>>,
|
||||
/// For checksum fields: whether it matches the computed value.
|
||||
pub checksum_valid: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
#[serde(untagged)]
|
||||
pub enum ParsedValue {
|
||||
Uint(u64),
|
||||
Int(i64),
|
||||
Float(f64),
|
||||
Bytes(Vec<u8>),
|
||||
Str(String),
|
||||
Flags(Vec<FlagValue>),
|
||||
None,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct FlagValue {
|
||||
pub bit: u8,
|
||||
pub name: String,
|
||||
pub set: bool,
|
||||
}
|
||||
|
||||
struct Cursor<'a> {
|
||||
data: &'a [u8],
|
||||
pos: usize,
|
||||
}
|
||||
|
||||
impl<'a> Cursor<'a> {
|
||||
fn new(data: &'a [u8]) -> Self {
|
||||
Self { data, pos: 0 }
|
||||
}
|
||||
|
||||
fn remaining(&self) -> usize {
|
||||
self.data.len().saturating_sub(self.pos)
|
||||
}
|
||||
|
||||
fn read_bytes(&mut self, n: usize) -> Result<&[u8], String> {
|
||||
if self.pos + n > self.data.len() {
|
||||
return Err(format!(
|
||||
"Not enough bytes at offset {}: need {n}, have {}",
|
||||
self.pos,
|
||||
self.remaining()
|
||||
));
|
||||
}
|
||||
let start = self.pos;
|
||||
self.pos += n;
|
||||
Ok(&self.data[start..start + n])
|
||||
}
|
||||
|
||||
fn read_u8(&mut self) -> Result<u8, String> {
|
||||
Ok(self.read_bytes(1)?[0])
|
||||
}
|
||||
|
||||
fn read_u16(&mut self, endian: &Endian) -> Result<u16, String> {
|
||||
let b = self.read_bytes(2)?;
|
||||
Ok(match endian {
|
||||
Endian::Big => u16::from_be_bytes([b[0], b[1]]),
|
||||
Endian::Little => u16::from_le_bytes([b[0], b[1]]),
|
||||
})
|
||||
}
|
||||
|
||||
fn read_u32(&mut self, endian: &Endian) -> Result<u32, String> {
|
||||
let b = self.read_bytes(4)?;
|
||||
Ok(match endian {
|
||||
Endian::Big => u32::from_be_bytes([b[0], b[1], b[2], b[3]]),
|
||||
Endian::Little => u32::from_le_bytes([b[0], b[1], b[2], b[3]]),
|
||||
})
|
||||
}
|
||||
|
||||
fn read_u64(&mut self, endian: &Endian) -> Result<u64, String> {
|
||||
let b = self.read_bytes(8)?;
|
||||
let arr: [u8; 8] = b.try_into().unwrap();
|
||||
Ok(match endian {
|
||||
Endian::Big => u64::from_be_bytes(arr),
|
||||
Endian::Little => u64::from_le_bytes(arr),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_fields(data: &[u8], fields: &[FieldDef]) -> Result<ParseResult, String> {
|
||||
let mut cursor = Cursor::new(data);
|
||||
let mut parsed = Vec::new();
|
||||
// Track named uint fields for dynamic count resolution.
|
||||
let mut named_uints: HashMap<String, usize> = HashMap::new();
|
||||
|
||||
parse_fields_inner(data, &mut cursor, fields, &mut parsed, &mut named_uints)?;
|
||||
|
||||
Ok(ParseResult {
|
||||
fields: parsed,
|
||||
total_bytes: data.len(),
|
||||
consumed_bytes: cursor.pos,
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_fields_inner(
|
||||
full_data: &[u8],
|
||||
cursor: &mut Cursor,
|
||||
fields: &[FieldDef],
|
||||
out: &mut Vec<ParsedField>,
|
||||
named_uints: &mut HashMap<String, usize>,
|
||||
) -> Result<(), String> {
|
||||
// Default endian if not specified in field.
|
||||
let global_endian = Endian::Big;
|
||||
|
||||
for field in fields {
|
||||
let endian = field.endian.as_ref().unwrap_or(&global_endian);
|
||||
let offset = cursor.pos;
|
||||
|
||||
let (value, size, children, checksum_valid) = match &field.kind {
|
||||
FieldKind::Uint8 => {
|
||||
let v = cursor.read_u8()? as u64;
|
||||
named_uints.insert(field.name.clone(), v as usize);
|
||||
(ParsedValue::Uint(v), 1, None, None)
|
||||
}
|
||||
FieldKind::Uint16 => {
|
||||
let v = cursor.read_u16(endian)? as u64;
|
||||
named_uints.insert(field.name.clone(), v as usize);
|
||||
(ParsedValue::Uint(v), 2, None, None)
|
||||
}
|
||||
FieldKind::Uint32 => {
|
||||
let v = cursor.read_u32(endian)? as u64;
|
||||
named_uints.insert(field.name.clone(), v as usize);
|
||||
(ParsedValue::Uint(v), 4, None, None)
|
||||
}
|
||||
FieldKind::Uint64 => {
|
||||
let v = cursor.read_u64(endian)?;
|
||||
(ParsedValue::Uint(v), 8, None, None)
|
||||
}
|
||||
FieldKind::Int8 => {
|
||||
let v = cursor.read_u8()? as i8;
|
||||
(ParsedValue::Int(v as i64), 1, None, None)
|
||||
}
|
||||
FieldKind::Int16 => {
|
||||
let raw = cursor.read_u16(endian)?;
|
||||
let v = raw as i16;
|
||||
(ParsedValue::Int(v as i64), 2, None, None)
|
||||
}
|
||||
FieldKind::Int32 => {
|
||||
let raw = cursor.read_u32(endian)?;
|
||||
let v = raw as i32;
|
||||
(ParsedValue::Int(v as i64), 4, None, None)
|
||||
}
|
||||
FieldKind::Float32 => {
|
||||
let raw = cursor.read_u32(endian)?;
|
||||
let v = f32::from_bits(raw) as f64;
|
||||
(ParsedValue::Float(v), 4, None, None)
|
||||
}
|
||||
FieldKind::Float64 => {
|
||||
let raw = cursor.read_u64(endian)?;
|
||||
let v = f64::from_bits(raw);
|
||||
(ParsedValue::Float(v), 8, None, None)
|
||||
}
|
||||
FieldKind::Bitflags8 => {
|
||||
let byte = cursor.read_u8()?;
|
||||
let flags = resolve_flags(byte as u64, field.flags.as_deref().unwrap_or(&[]));
|
||||
(ParsedValue::Flags(flags), 1, None, None)
|
||||
}
|
||||
FieldKind::Bitflags16 => {
|
||||
let raw = cursor.read_u16(endian)? as u64;
|
||||
let flags = resolve_flags(raw, field.flags.as_deref().unwrap_or(&[]));
|
||||
(ParsedValue::Flags(flags), 2, None, None)
|
||||
}
|
||||
FieldKind::Bytes => {
|
||||
let len = field.length.ok_or_else(|| {
|
||||
format!("Field '{}': 'bytes' type requires 'length'", field.name)
|
||||
})?;
|
||||
let b = cursor.read_bytes(len)?.to_vec();
|
||||
(ParsedValue::Bytes(b), len, None, None)
|
||||
}
|
||||
FieldKind::Padding => {
|
||||
let len = field.length.unwrap_or(1);
|
||||
cursor.read_bytes(len)?;
|
||||
(ParsedValue::None, len, None, None)
|
||||
}
|
||||
FieldKind::StringFixed => {
|
||||
let len = field.length.ok_or_else(|| {
|
||||
format!("Field '{}': 'string_fixed' requires 'length'", field.name)
|
||||
})?;
|
||||
let raw = cursor.read_bytes(len)?.to_vec();
|
||||
let s = String::from_utf8_lossy(&raw)
|
||||
.trim_end_matches('\0')
|
||||
.to_string();
|
||||
(ParsedValue::Str(s), len, None, None)
|
||||
}
|
||||
FieldKind::StringLp8 => {
|
||||
let len = cursor.read_u8()? as usize;
|
||||
let raw = cursor.read_bytes(len)?.to_vec();
|
||||
let s = String::from_utf8_lossy(&raw).into_owned();
|
||||
(ParsedValue::Str(s), 1 + len, None, None)
|
||||
}
|
||||
FieldKind::StringLp16 => {
|
||||
let len = cursor.read_u16(endian)? as usize;
|
||||
let raw = cursor.read_bytes(len)?.to_vec();
|
||||
let s = String::from_utf8_lossy(&raw).into_owned();
|
||||
(ParsedValue::Str(s), 2 + len, None, None)
|
||||
}
|
||||
FieldKind::Crc16 => {
|
||||
let stored = cursor.read_u16(endian)?;
|
||||
let valid = if let Some(range) = field.checksum_range {
|
||||
let slice = full_data
|
||||
.get(range[0]..range[1])
|
||||
.ok_or_else(|| format!("CRC range {:?} out of bounds", range))?;
|
||||
let computed = compute_crc16(slice);
|
||||
Some(computed == stored)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
(ParsedValue::Uint(stored as u64), 2, None, valid)
|
||||
}
|
||||
FieldKind::Crc32 => {
|
||||
let stored = cursor.read_u32(endian)?;
|
||||
let valid = if let Some(range) = field.checksum_range {
|
||||
let slice = full_data
|
||||
.get(range[0]..range[1])
|
||||
.ok_or_else(|| format!("CRC range {:?} out of bounds", range))?;
|
||||
let computed = compute_crc32(slice);
|
||||
Some(computed == stored)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
(ParsedValue::Uint(stored as u64), 4, None, valid)
|
||||
}
|
||||
FieldKind::Repeated => {
|
||||
let inner_fields = field.fields.as_deref().ok_or_else(|| {
|
||||
format!("Field '{}': 'repeated' requires 'fields'", field.name)
|
||||
})?;
|
||||
let count = match field.count.as_ref() {
|
||||
Some(CountSpec::Fixed(n)) => *n,
|
||||
Some(CountSpec::Field(name)) => *named_uints
|
||||
.get(name)
|
||||
.ok_or_else(|| format!("Count field '{}' not found", name))?,
|
||||
None => {
|
||||
return Err(format!(
|
||||
"Field '{}': 'repeated' requires 'count'",
|
||||
field.name
|
||||
))
|
||||
}
|
||||
};
|
||||
|
||||
let start = cursor.pos;
|
||||
let mut children_out = Vec::new();
|
||||
let mut child_named = named_uints.clone();
|
||||
for _ in 0..count {
|
||||
let mut iteration = Vec::new();
|
||||
parse_fields_inner(
|
||||
full_data,
|
||||
cursor,
|
||||
inner_fields,
|
||||
&mut iteration,
|
||||
&mut child_named,
|
||||
)?;
|
||||
children_out.extend(iteration);
|
||||
}
|
||||
let size = cursor.pos - start;
|
||||
(ParsedValue::None, size, Some(children_out), None)
|
||||
}
|
||||
};
|
||||
|
||||
out.push(ParsedField {
|
||||
name: field.name.clone(),
|
||||
kind: format!("{:?}", field.kind),
|
||||
offset,
|
||||
size,
|
||||
value,
|
||||
description: field.description.clone(),
|
||||
children,
|
||||
checksum_valid,
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn resolve_flags(raw: u64, defs: &[crate::schema::FlagDef]) -> Vec<FlagValue> {
|
||||
defs.iter()
|
||||
.map(|f| FlagValue {
|
||||
bit: f.bit,
|
||||
name: f.name.clone(),
|
||||
set: (raw >> f.bit) & 1 == 1,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// A full schema describing a binary frame layout.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Schema {
|
||||
/// Human-readable name for this schema.
|
||||
pub name: Option<String>,
|
||||
/// Endianness applied globally unless overridden per field.
|
||||
#[serde(default = "default_endian")]
|
||||
pub endian: Endian,
|
||||
/// Ordered list of fields to parse.
|
||||
pub fields: Vec<FieldDef>,
|
||||
}
|
||||
|
||||
fn default_endian() -> Endian {
|
||||
Endian::Big
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Endian {
|
||||
Big,
|
||||
Little,
|
||||
}
|
||||
|
||||
/// A single field definition.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct FieldDef {
|
||||
/// Display name.
|
||||
pub name: String,
|
||||
/// Field type.
|
||||
#[serde(rename = "type")]
|
||||
pub kind: FieldKind,
|
||||
/// Override global endianness for this field.
|
||||
pub endian: Option<Endian>,
|
||||
/// Description / comment shown in the tree.
|
||||
pub description: Option<String>,
|
||||
/// For bitflags: the flag definitions.
|
||||
pub flags: Option<Vec<FlagDef>>,
|
||||
/// For `bytes` type: number of bytes (required).
|
||||
/// For `string_lp8` / `string_lp16`: omit (length is read from data).
|
||||
/// For other types: derived from type width.
|
||||
pub length: Option<usize>,
|
||||
/// For `crc16` / `crc32`: byte range to checksum [start, end) relative to frame start.
|
||||
pub checksum_range: Option<[usize; 2]>,
|
||||
/// For `repeated`: how many repetitions (constant or from a previously parsed field name).
|
||||
pub count: Option<CountSpec>,
|
||||
/// For `repeated`: the inner fields to repeat.
|
||||
pub fields: Option<Vec<FieldDef>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum FieldKind {
|
||||
/// 1 byte unsigned.
|
||||
Uint8,
|
||||
/// 2 bytes unsigned.
|
||||
Uint16,
|
||||
/// 4 bytes unsigned.
|
||||
Uint32,
|
||||
/// 8 bytes unsigned.
|
||||
Uint64,
|
||||
/// 1 byte signed.
|
||||
Int8,
|
||||
/// 2 bytes signed.
|
||||
Int16,
|
||||
/// 4 bytes signed.
|
||||
Int32,
|
||||
/// 4 bytes float.
|
||||
Float32,
|
||||
/// 8 bytes float.
|
||||
Float64,
|
||||
/// 1-byte bitfield with named flags.
|
||||
Bitflags8,
|
||||
/// 2-byte bitfield with named flags.
|
||||
Bitflags16,
|
||||
/// Raw bytes of `length`.
|
||||
Bytes,
|
||||
/// Null-terminated string of `length` bytes.
|
||||
StringFixed,
|
||||
/// Pascal-style: 1-byte length prefix, then UTF-8 bytes.
|
||||
StringLp8,
|
||||
/// Pascal-style: 2-byte length prefix (respects endian), then UTF-8 bytes.
|
||||
StringLp16,
|
||||
/// CRC-16/CCITT checksum (2 bytes).
|
||||
Crc16,
|
||||
/// CRC-32 checksum (4 bytes).
|
||||
Crc32,
|
||||
/// Repeat inner `fields` `count` times.
|
||||
Repeated,
|
||||
/// Skip / padding bytes.
|
||||
Padding,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct FlagDef {
|
||||
/// Bit index (0 = LSB).
|
||||
pub bit: u8,
|
||||
pub name: String,
|
||||
pub description: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(untagged)]
|
||||
pub enum CountSpec {
|
||||
/// Literal count.
|
||||
Fixed(usize),
|
||||
/// Name of a previously parsed uint field holding the count.
|
||||
Field(String),
|
||||
}
|
||||
@@ -0,0 +1,297 @@
|
||||
use hex_pigeon_parser::checksum::{compute_crc16, compute_crc32};
|
||||
use hex_pigeon_parser::{
|
||||
parse_fields, CountSpec, Endian, FieldDef, FieldKind, FlagDef, ParsedValue, Schema,
|
||||
};
|
||||
|
||||
fn field(name: &str, kind: FieldKind) -> FieldDef {
|
||||
FieldDef {
|
||||
name: name.to_string(),
|
||||
kind,
|
||||
endian: None,
|
||||
description: None,
|
||||
flags: None,
|
||||
length: None,
|
||||
checksum_range: None,
|
||||
count: None,
|
||||
fields: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn field_len(name: &str, kind: FieldKind, length: usize) -> FieldDef {
|
||||
let mut f = field(name, kind);
|
||||
f.length = Some(length);
|
||||
f
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn schema_deserializes_from_json() {
|
||||
let json = r#"{
|
||||
"name": "Test",
|
||||
"endian": "little",
|
||||
"fields": [{ "name": "id", "type": "uint8" }]
|
||||
}"#;
|
||||
let schema: Schema = serde_json::from_str(json).expect("schema JSON");
|
||||
assert_eq!(schema.name.as_deref(), Some("Test"));
|
||||
assert_eq!(schema.endian, Endian::Little);
|
||||
assert_eq!(schema.fields.len(), 1);
|
||||
assert_eq!(schema.fields[0].kind, FieldKind::Uint8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_integer_types_big_endian() {
|
||||
let data = [
|
||||
0x12,
|
||||
0x12, 0x34,
|
||||
0x12, 0x34, 0x56, 0x78,
|
||||
0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0,
|
||||
0xFE,
|
||||
0xFF, 0xF0,
|
||||
0x80, 0x00, 0x00, 0x01,
|
||||
];
|
||||
let fields = vec![
|
||||
field("u8", FieldKind::Uint8),
|
||||
field("u16", FieldKind::Uint16),
|
||||
field("u32", FieldKind::Uint32),
|
||||
field("u64", FieldKind::Uint64),
|
||||
field("i8", FieldKind::Int8),
|
||||
field("i16", FieldKind::Int16),
|
||||
field("i32", FieldKind::Int32),
|
||||
];
|
||||
let result = parse_fields(&data, &fields).expect("parse");
|
||||
|
||||
assert_eq!(result.consumed_bytes, 22);
|
||||
assert!(matches!(result.fields[0].value, ParsedValue::Uint(0x12)));
|
||||
assert!(matches!(result.fields[1].value, ParsedValue::Uint(0x1234)));
|
||||
assert!(matches!(result.fields[2].value, ParsedValue::Uint(0x12345678)));
|
||||
assert!(matches!(result.fields[3].value, ParsedValue::Uint(0x123456789ABCDEF0)));
|
||||
assert!(matches!(result.fields[4].value, ParsedValue::Int(-2)));
|
||||
assert!(matches!(result.fields[5].value, ParsedValue::Int(-16)));
|
||||
assert!(matches!(result.fields[6].value, ParsedValue::Int(-2147483647)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_integer_types_little_endian() {
|
||||
let data = [0x34, 0x12];
|
||||
let mut f = field("u16", FieldKind::Uint16);
|
||||
f.endian = Some(Endian::Little);
|
||||
let result = parse_fields(&data, &[f]).expect("parse");
|
||||
assert!(matches!(result.fields[0].value, ParsedValue::Uint(0x1234)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_float_types() {
|
||||
let f32_bits = 1.0f32.to_bits();
|
||||
let f64_bits = 2.5f64.to_bits();
|
||||
let mut data = Vec::new();
|
||||
data.extend_from_slice(&f32_bits.to_be_bytes());
|
||||
data.extend_from_slice(&f64_bits.to_be_bytes());
|
||||
|
||||
let fields = vec![field("f32", FieldKind::Float32), field("f64", FieldKind::Float64)];
|
||||
let result = parse_fields(&data, &fields).expect("parse");
|
||||
|
||||
match &result.fields[0].value {
|
||||
ParsedValue::Float(v) => assert!((v - 1.0).abs() < f64::EPSILON),
|
||||
other => panic!("expected float32, got {other:?}"),
|
||||
}
|
||||
match &result.fields[1].value {
|
||||
ParsedValue::Float(v) => assert!((v - 2.5).abs() < f64::EPSILON),
|
||||
other => panic!("expected float64, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_bitflags() {
|
||||
let mut f8 = field("flags8", FieldKind::Bitflags8);
|
||||
f8.flags = Some(vec![
|
||||
FlagDef {
|
||||
bit: 0,
|
||||
name: "A".into(),
|
||||
description: None,
|
||||
},
|
||||
FlagDef {
|
||||
bit: 3,
|
||||
name: "D".into(),
|
||||
description: None,
|
||||
},
|
||||
]);
|
||||
let mut f16 = field("flags16", FieldKind::Bitflags16);
|
||||
f16.flags = Some(vec![FlagDef {
|
||||
bit: 1,
|
||||
name: "B".into(),
|
||||
description: None,
|
||||
}]);
|
||||
|
||||
let result = parse_fields(&[0b0000_0101, 0x00, 0b0000_0010], &[f8, f16]).expect("parse");
|
||||
|
||||
match &result.fields[0].value {
|
||||
ParsedValue::Flags(flags) => {
|
||||
assert!(flags.iter().find(|f| f.name == "A").unwrap().set);
|
||||
assert!(!flags.iter().find(|f| f.name == "D").unwrap().set);
|
||||
}
|
||||
other => panic!("expected flags8, got {other:?}"),
|
||||
}
|
||||
match &result.fields[1].value {
|
||||
ParsedValue::Flags(flags) => assert!(flags[0].set),
|
||||
other => panic!("expected flags16, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_bytes_padding_and_strings() {
|
||||
let data = [
|
||||
0xAA, 0xBB, 0xCC, // bytes[3]
|
||||
0x00, 0x00, // padding[2]
|
||||
b'H', b'i', 0x00, 0x00, // string_fixed[4] -> "Hi"
|
||||
0x03, b'F', b'O', b'O', // string_lp8
|
||||
0x00, 0x02, b'B', b'R', // string_lp16 big-endian length
|
||||
];
|
||||
|
||||
let fields = vec![
|
||||
field_len("raw", FieldKind::Bytes, 3),
|
||||
field_len("pad", FieldKind::Padding, 2),
|
||||
field_len("fixed", FieldKind::StringFixed, 4),
|
||||
field("lp8", FieldKind::StringLp8),
|
||||
field("lp16", FieldKind::StringLp16),
|
||||
];
|
||||
let result = parse_fields(&data, &fields).expect("parse");
|
||||
|
||||
assert!(matches!(&result.fields[0].value, ParsedValue::Bytes(v) if v == &[0xAA, 0xBB, 0xCC]));
|
||||
assert!(matches!(result.fields[1].value, ParsedValue::None));
|
||||
assert!(matches!(&result.fields[2].value, ParsedValue::Str(s) if s == "Hi"));
|
||||
assert!(matches!(&result.fields[3].value, ParsedValue::Str(s) if s == "FOO"));
|
||||
assert!(matches!(&result.fields[4].value, ParsedValue::Str(s) if s == "BR"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validates_crc16_and_crc32() {
|
||||
let payload = [0x01, 0x02, 0x03, 0x04];
|
||||
let crc16 = compute_crc16(&payload);
|
||||
let crc32 = compute_crc32(&payload);
|
||||
|
||||
let mut data = payload.to_vec();
|
||||
data.extend_from_slice(&crc16.to_be_bytes());
|
||||
data.extend_from_slice(&crc32.to_be_bytes());
|
||||
|
||||
let mut crc16_field = field("c16", FieldKind::Crc16);
|
||||
crc16_field.checksum_range = Some([0, 4]);
|
||||
let mut crc32_field = field("c32", FieldKind::Crc32);
|
||||
crc32_field.checksum_range = Some([0, 4]);
|
||||
|
||||
let fields = vec![
|
||||
field_len("payload", FieldKind::Bytes, 4),
|
||||
crc16_field,
|
||||
crc32_field,
|
||||
];
|
||||
let result = parse_fields(&data, &fields).expect("parse");
|
||||
assert_eq!(result.fields[1].checksum_valid, Some(true));
|
||||
assert_eq!(result.fields[2].checksum_valid, Some(true));
|
||||
|
||||
let mut bad = data.clone();
|
||||
bad[6] ^= 0xFF;
|
||||
let mut crc32_bad = field("c32", FieldKind::Crc32);
|
||||
crc32_bad.checksum_range = Some([0, 4]);
|
||||
let fields = vec![
|
||||
field_len("payload", FieldKind::Bytes, 4),
|
||||
crc32_bad,
|
||||
];
|
||||
let result = parse_fields(&bad, &fields).expect("parse");
|
||||
assert_eq!(result.fields[1].checksum_valid, Some(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_repeated_fixed_and_dynamic_count() {
|
||||
let data = [0x02, 0x10, 0x20, 0x11, 0x21];
|
||||
|
||||
let repeated_fixed = FieldDef {
|
||||
name: "items".into(),
|
||||
kind: FieldKind::Repeated,
|
||||
endian: None,
|
||||
description: None,
|
||||
flags: None,
|
||||
length: None,
|
||||
checksum_range: None,
|
||||
count: Some(CountSpec::Fixed(2)),
|
||||
fields: Some(vec![field("val", FieldKind::Uint8)]),
|
||||
};
|
||||
let result = parse_fields(&[0x10, 0x20, 0x11, 0x21], &[repeated_fixed]).expect("parse");
|
||||
let children = result.fields[0].children.as_ref().expect("children");
|
||||
assert_eq!(children.len(), 2);
|
||||
assert!(matches!(children[0].value, ParsedValue::Uint(0x10)));
|
||||
assert!(matches!(children[1].value, ParsedValue::Uint(0x20)));
|
||||
|
||||
let repeated_dynamic = FieldDef {
|
||||
name: "list".into(),
|
||||
kind: FieldKind::Repeated,
|
||||
endian: None,
|
||||
description: None,
|
||||
flags: None,
|
||||
length: None,
|
||||
checksum_range: None,
|
||||
count: Some(CountSpec::Field("count".into())),
|
||||
fields: Some(vec![field("val", FieldKind::Uint8)]),
|
||||
};
|
||||
let result = parse_fields(&data, &[field("count", FieldKind::Uint8), repeated_dynamic]).expect("parse");
|
||||
let children = result.fields[1].children.as_ref().expect("children");
|
||||
assert_eq!(children.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn errors_on_truncated_buffer() {
|
||||
let result = parse_fields(&[0x01], &[field("u16", FieldKind::Uint16)]);
|
||||
assert!(result.is_err());
|
||||
assert!(result.unwrap_err().contains("Not enough bytes"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn errors_on_missing_required_field_options() {
|
||||
let err = parse_fields(&[0x01], &[field("raw", FieldKind::Bytes)]).unwrap_err();
|
||||
assert!(err.contains("requires 'length'"));
|
||||
|
||||
let repeated = FieldDef {
|
||||
name: "r".into(),
|
||||
kind: FieldKind::Repeated,
|
||||
endian: None,
|
||||
description: None,
|
||||
flags: None,
|
||||
length: None,
|
||||
checksum_range: None,
|
||||
count: Some(CountSpec::Fixed(1)),
|
||||
fields: None,
|
||||
};
|
||||
let err = parse_fields(&[0x01], &[repeated]).unwrap_err();
|
||||
assert!(err.contains("requires 'fields'"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_example_protocol_frame() {
|
||||
let header = [
|
||||
0xFF, 0x05, b'H', b'e', b'l', b'l', b'o', 0x00, 0x01, 0x02, 0x03, b'A', b'B', b'C',
|
||||
b'D',
|
||||
];
|
||||
let crc32 = compute_crc32(&header[..11]);
|
||||
let mut data = header.to_vec();
|
||||
data.extend_from_slice(&crc32.to_be_bytes());
|
||||
data.extend_from_slice(&[0x00, 0x03]); // flags: ACK + SYN
|
||||
|
||||
let schema_json = include_str!("../../frontend/src/fixtures/example-schema.json");
|
||||
let schema: Schema = serde_json::from_str(schema_json).expect("example schema");
|
||||
let result = parse_fields(&data, &schema.fields).expect("example frame");
|
||||
|
||||
assert_eq!(result.total_bytes, data.len());
|
||||
assert_eq!(result.consumed_bytes, data.len());
|
||||
assert_eq!(result.fields.len(), 7);
|
||||
|
||||
assert!(matches!(result.fields[0].value, ParsedValue::Uint(0xFF)));
|
||||
assert!(matches!(&result.fields[2].value, ParsedValue::Str(s) if s == "Hello"));
|
||||
assert!(matches!(&result.fields[4].value, ParsedValue::Str(s) if s == "ABCD"));
|
||||
assert_eq!(result.fields[5].checksum_valid, Some(true));
|
||||
|
||||
match &result.fields[6].value {
|
||||
ParsedValue::Flags(flags) => {
|
||||
assert!(flags.iter().find(|f| f.name == "ACK").unwrap().set);
|
||||
assert!(flags.iter().find(|f| f.name == "SYN").unwrap().set);
|
||||
assert!(!flags.iter().find(|f| f.name == "FIN").unwrap().set);
|
||||
}
|
||||
other => panic!("expected flags, got {other:?}"),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
{ pkgs ? import <nixpkgs> {} }:
|
||||
|
||||
pkgs.mkShell {
|
||||
name = "hex-pigeon-dev";
|
||||
|
||||
buildInputs = with pkgs; [
|
||||
# Rust + WASM toolchain
|
||||
rustup
|
||||
wasm-pack
|
||||
binaryen # wasm-opt
|
||||
|
||||
# Node / frontend
|
||||
nodejs_22
|
||||
|
||||
# Utilities
|
||||
pkg-config
|
||||
openssl
|
||||
];
|
||||
|
||||
shellHook = ''
|
||||
export RUSTUP_HOME="$HOME/.rustup"
|
||||
export CARGO_HOME="$HOME/.cargo"
|
||||
export PATH="$CARGO_HOME/bin:$PATH"
|
||||
|
||||
# Install stable + wasm32 target on first run
|
||||
rustup toolchain install stable 2>/dev/null || true
|
||||
rustup default stable 2>/dev/null || true
|
||||
rustup target add wasm32-unknown-unknown 2>/dev/null || true
|
||||
|
||||
echo "HexPigeon dev shell ready"
|
||||
echo " • Build WASM : cd parser-wasm && wasm-pack build --target web --out-dir ../frontend/src/wasm"
|
||||
echo " • Frontend : cd frontend && npm install && npm run dev"
|
||||
'';
|
||||
}
|
||||
Reference in New Issue
Block a user