# varch
**Repository Path**: zzflytang/varch
## Basic Information
- **Project Name**: varch
- **Description**: 嵌入式C语言常用代码模块库,包含了嵌入式中常用的算法库(查找、校验、过滤、哈希、排序等)、数据结构/容器库(通用队列、栈、堆、列表、动态数组、字符串、集合、字典、映射、图等)、解析器库(csv、ini、json、xml等)、数学库(大数运算、数学运算)、C语言协程库、独立C语言std库、工具库等等。
具有简单, 通用, 高效的特点,目的为了学习以及在开发中拿来就用,提高开发效率以及代码可靠稳定性。
- **Primary Language**: Unknown
- **License**: GPL-2.0
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 1
- **Forks**: 202
- **Created**: 2026-12-04
- **Last Updated**: 2026-12-04
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README
# varch (we-architecture)

[](https://gitee.com/Lamdonn/varch)
[](LICENSE)
[](#)
[](#)
[](#)
[](mailto:Lamdonn@163.com)
**A lightweight, modular, freestanding, zero-coupling C/C++ architecture library for embedded systems and beyond.**
[中文版 (Chinese)](README.md) | [Gitee Repository](https://gitee.com/Lamdonn/varch) | [Documentation](doc/)
---
## 📖 Introduction
**varch** (*we-architecture*, meaning "our framework library") is a high-performance, modular infrastructure library meticulously crafted for embedded firmware development, systems-level programming, and general C/C++ projects.
The project encompasses 9 essential subsystems commonly required in embedded and systems engineering:
- **Algorithms & Digital Signal Processing** (PID controllers, Kalman & moving average filters, lookup-table CRC, sorting algorithms, KMP/binary search, cryptography, discrete hashing);
- **Generic Data Structures & Containers** (deque, lock-free circular queue, binary heap, red-black tree Map/Set, chained hash Dict, dynamic Vector, safe string, tree, graph);
- **Multi-Protocol Structured Parsers** (JSON, YAML, XML, INI, CSV, TXLS);
- **Arbitrary-Precision Arithmetic Engine** (arbitrary-width signed/unsigned big integers `intl`/`uintl`, IEEE-754 arbitrary-precision floating-point `floatl`, transcendental functions `flmath`, and modern C++11 template abstractions);
- **System Services & Facilities** (cooperative scheduler `kern`, slab block allocator `valloc`, hierarchical state machine `fsm`, multi-level ANSI color logger `vlog`, serial link universal protocol `slup`, IPC message bus `icom`, lightweight coroutine engine `coroutine`);
- **Freestanding C Standard Runtime Replacement** (`-ffreestanding` with zero external libc dependencies, featuring completely self-contained memory, string, and math routines).
Adhering strictly to the principles of **simplicity, universality, efficiency, and determinism**, each module in `varch` is designed to be highly orthogonal, allowing developers to extract and use individual components with zero overhead and minimal friction.
---
## 🌟 Core Architectural Philosophies & Features
1. **Orthogonal Modularity & Zero Mandatory Coupling (High Cohesion & Low Coupling)**
- Unnecessary cross-module hierarchical dependencies are strictly prohibited. Except for fundamental platform types, each component is self-contained and decoupled using generic pointers (`void *`).
- Developers can **extract any single `.c` and `.h` pair and drop it directly into an MCU project**, without having to pull in the entire library.
2. **Determinism & Zero Mandatory Heap Allocation (0 Malloc / 0 Free in Math)**
- **Zero Heap in Big Number Math**: All intermediate buffers in `intl` (big integer), `uintl` (unsigned big integer), `floatl` (big float), and `flmath` are allocated strictly on the **C99 stack via Variable Length Arrays (VLA)**. No `malloc` or `free` calls occur throughout the entire arithmetic lifecycle.
- **Static Buffer Injection in Containers**: Data structures such as `queue` and `stack` allow users to inject pre-allocated static memory buffers (`base`), completely eliminating memory fragmentation and runtime exhaustion risks in mission-critical embedded systems.
3. **Autonomous Freestanding C Runtime Replacement (-ffreestanding 0 libc)**
- The `02_vstd` subsystem implements complete memory manipulation (`vmem`), string processing (`vstring`), stdlib algorithms (`vstdlib`), single/double-precision software math (`vmath`), and character classification (`vctype`).
- Runs directly on bare-metal MCUs without requiring Newlib, Glibc, or any underlying OS system calls.
4. **Dual-Mode Execution Architecture (Standalone CLI & Integrated Console)**
- Every module follows a unified dual-mode architecture:
- **Standalone CLI Mode** (`-DTEST_TARGET_`): Can be compiled directly into a self-contained executable with option parsing (`-e`, `-h`, `-v`), accelerating CI/CD testing and algorithmic verification;
- **Embedded App Mode**: Automatically registers into the interactive console command registry via `init_export_app` for immediate on-device testing.
5. **Modern C++11 Template Wrappers**
- High-precision arithmetic features zero-cost C++11 wrappers (`intl.hpp`, `floatl.hpp`), exporting type-safe template classes `varch::intl`, `varch::uintl`, and `varch::floatl`.
- Preserves 100% stack allocation (standard layout), offering full operator overloading, mixed scalar arithmetic, and stream `<<` support.
---
## 🏛️ Overall System Architecture
`varch` employs a strictly orthogonal component matrix architecture:

### Functional Subsystem Microarchitectures
Comprehensive, publication-grade architectural diagrams are provided in the `image/` directory (editable natively via VS Code Draw.io extension):
| No. | Category | Core Responsibilities & Modules | Diagram File (`image/*.drawio`) |
|:---:|:---|:---|:---|
| **00** | `00_application` | Application entry `main`, GNU section link-time auto-export (`init.h`), interactive console shell | [00_application_architecture.drawio](image/00_application_architecture.drawio) |
| **01** | `01_general` | Cooperative scheduler `kern`, multi-action button engine `button`, slab allocator `valloc`, hierarchical FSM `fsm`, logger `vlog`, utilities (`date`/`calculate`/`arg`/`oscp`/`tool`/`artf`) | [01_general_architecture.drawio](image/01_general_architecture.drawio) *(Contains multiple sub-diagram tabs)* |
| **02** | `02_vstd` | Autonomous standard C library: `vmem`, `vstring`, `vstdlib`, `vmath`, `vctype`, `vstdint`, `vstddef` | [02_vstd_architecture.drawio](image/02_vstd_architecture.drawio) |
| **03** | `03_container` | Generic containers & bit/byte streams: `list`, `slist`, `dlist`, `queue`, `rqueue`, `ringbuf`, `bitmap`, `vector`, `deque`, `map`, `dict`, `stack`, `set`, `heap`, `tree`, `graph`, `str` | [03_container_architecture.drawio](image/03_container_architecture.drawio) |
| **04** | `04_algorithm` | Algorithm suite: closed-loop `pid`, filter suite `filter` (Butterworth/clamping/complementary/Kalman), compression suite `compress` (LZ4/RLE/LZSS), bitstream codec `bpack`, `base64` codec, table-driven `crc`, `sort`, `search`, `encrypt`, `hash`, `check` | [04_algorithm_architecture.drawio](image/04_algorithm_architecture.drawio) |
| **05** | `05_parser` | Multi-protocol parsers: GNSS/GPS `nmea`, binary `protobuf`, `json` DOM tree, `yaml` state machine, `xml` tag tree, `ini` sections, `csv` / `txls` tables | [05_parser_architecture.drawio](image/05_parser_architecture.drawio) |
| **06** | `06_performance` | Profiling & communication: unit testing `unitt`, message bus `icom`, load monitor `cpul`, memory `ramt`, flash `romt`, serial protocol `slup`, CAN tester `cant` | [06_performance_architecture.drawio](image/06_performance_architecture.drawio) |
| **07** | `07_math` | Arbitrary-precision math: big integer `intl`/`uintl`, big float `floatl`, transcendental functions `flmath`, C++ templates | [07_math_architecture.drawio](image/07_math_architecture.drawio) |
| **08** | `08_coroutine` | Cooperative concurrency: fiber context switching `coroutine`, async IO poller `coroutine_io`, synchronization primitives, channels | [08_coroutine_architecture.drawio](image/08_coroutine_architecture.drawio) |
---
## 📦 Module Directory & Reference
| Module | Version | Documentation | Source Directory | Description |
|:---|:---:|:---:|:---|:---|
| **overall** | 00.03.05 | [README](README.en.md) | [./](./) | Overall architectural overview and guidelines |
| **init** | 01.00.00 | [link](doc/init.en.md) | [source/00_application](source/00_application/) | Link-time section priority auto-export framework (Level 1..4) |
| **console** | 01.00.01 | [link](doc/console.en.md) | [source/00_application/console](source/00_application/console/) | Interactive console shell with line editing, history buffer, and Tab completion |
| **arg** | 01.00.00 | [link](doc/arg.en.md) | [source/01_general](source/01_general/) | Command-line variable arguments and option parser |
| **button** | 01.00.00 | [link](doc/button.en.md) | [source/01_general](source/01_general/) | Multi-action event-driven button engine with debouncing, multi-press, long-press, and custom timing |
| **calculate** | 01.01.00 | [link](doc/calculate.en.md) | [source/01_general](source/01_general/) | Shunting-yard expression parser for infix-to-RPN evaluation |
| **command** | 01.00.00 | [link](doc/command.md) | [source/01_general](source/01_general/) | Shell-like command tokenizer and dynamic command dispatcher |
| **artf** | 01.00.00 | [link](doc/artf.en.md) | [source/01_general](source/01_general/) | Dot-matrix ASCII art font and startup banner generator |
| **fsm** | 01.00.00 | [link](doc/fsm.en.md) | [source/01_general](source/01_general/) | Hierarchical finite state machine with enter/action/exit lifecycle hooks |
| **kern** | 01.00.00 | [link](doc/kern.en.md) | [source/01_general](source/01_general/) | Deterministic non-preemptive cooperative multi-tasking scheduler kernel |
| **oscp** | 01.00.00 | [link](doc/oscp.en.md) | [source/01_general](source/01_general/) | Object state control protocol for embedded variable waveform monitoring |
| **tool** | 01.01.00 | [link](doc/tool.en.md) | [source/01_general](source/01_general/) | Endian conversion, alignment macros, and bit manipulation utilities |
| **valloc** | 01.00.00 | [link](doc/valloc.en.md) | [source/01_general](source/01_general/) | Fixed-block slab memory pool, 0 fragmentation, O(1) bitmap indexing |
| **vlog** | 01.01.00 | [link](doc/vlog.en.md) | [source/01_general](source/01_general/) | Multi-level logger with ANSI terminal coloring, timestamps, and IO redirect |
| **date** | 01.00.00 | [link](doc/date.en.md) | [source/01_general](source/01_general/) | Calendar and timestamp routines, Unix epoch conversion, leap year detection |
| **vctype** | 01.00.00 | [link](doc/vctype.en.md) | [source/02_vstd](source/02_vstd/) | Freestanding character classification and case conversion |
| **vmath** | 01.00.00 | [link](doc/vmath.en.md) | [source/02_vstd](source/02_vstd/) | Bare-metal software math library (sqrt, trig, exp, log) |
| **vmem** | 01.00.00 | [link](doc/vmem.en.md) | [source/02_vstd](source/02_vstd/) | Raw memory operations: copy, set, move, and comparison (memcpy/memset) |
| **vstddef** | 01.00.00 | [link](doc/vstddef.en.md) | [source/02_vstd](source/02_vstd/) | Freestanding type definitions, `size_t`, `NULL`, `offsetof` macros |
| **vstdint** | 01.00.00 | [link](doc/vstdint.en.md) | [source/02_vstd](source/02_vstd/) | Fixed-width integer types (`uint8_t` ~ `uint64_t`) and limit macros |
| **vstdlib** | 01.00.00 | [link](doc/vstdlib.en.md) | [source/02_vstd](source/02_vstd/) | String/integer conversions, pseudo-random generator, qsort, and bsearch |
| **vstring** | 01.00.00 | [link](doc/vstring.en.md) | [source/02_vstd](source/02_vstd/) | Safe bounded string utilities (length, copy, concat, substring search) |
| **queue** | 01.00.00 | [link](doc/queue.en.md) | [source/03_container](source/03_container/) | Universal FIFO ring queue container (supports static external buffer, 0 heap) |
| **rqueue** | 01.00.03 | [link](doc/rqueue.en.md) | [source/03_container](source/03_container/) | Lightweight single-producer single-consumer (SPSC) lock-free ring buffer (ring-queue) |
| **ringbuf** | 01.00.00 | [link](doc/ringbuf.en.md) | [source/03_container](source/03_container/) | High-performance byte-stream ring buffer with peek lookahead and DMA zero-copy slices |
| **bitmap** | 01.00.00 | [link](doc/bitmap.en.md) | [source/03_container](source/03_container/) | High-performance bitmap and bit array library with contiguous zero search and bitwise logic |
| **slist** | 01.00.01 | [link](doc/slist.en.md) | [source/03_container](source/03_container/) | Linux-kernel-style intrusive singly linked list (single-link-list) controller |
| **dlist** | 01.00.01 | [link](doc/dlist.en.md) | [source/03_container](source/03_container/) | Linux-kernel-style intrusive circular doubly linked list (double-link-list) |
| **stack** | 01.00.00 | [link](doc/stack.en.md) | [source/03_container](source/03_container/) | Universal LIFO stack container (supports external static buffer) |
| **deque** | 01.00.00 | [link](doc/deque.en.md) | [source/03_container](source/03_container/) | Universal double-ended queue supporting O(1) front/back push and pop |
| **list** | 01.00.01 | [link](doc/list.en.md) | [source/03_container](source/03_container/) | Singly linked list container with internal cursor iterator caching |
| **vector** | 01.00.00 | [link](doc/vector.en.md) | [source/03_container](source/03_container/) | Contiguous dynamic auto-resizing vector supporting O(1) index addressing |
| **str** | 01.00.00 | [link](doc/str.en.md) | [source/03_container](source/03_container/) | Dynamic safe string class with append, substring, split, and replace |
| **dict** | 01.00.00 | [link](doc/dict.en.md) | [source/03_container](source/03_container/) | Chained hash table dictionary container, average O(1) retrieval |
| **heap** | 01.00.00 | [link](doc/heap.en.md) | [source/03_container](source/03_container/) | Binary min/max priority queue heap container |
| **set** | 01.00.01 | [link](doc/set.en.md) | [source/03_container](source/03_container/) | Unique element ordered set container based on Red-Black Tree |
| **map** | 01.00.01 | [link](doc/map.en.md) | [source/03_container](source/03_container/) | Key-value associative mapping container based on Red-Black Tree |
| **tree** | 01.00.00 | [link](doc/tree.en.md) | [source/03_container](source/03_container/) | Generic multi-way tree container with recursive traversal |
| **graph** | 01.00.00 | [link](doc/graph.en.md) | [source/03_container](source/03_container/) | Adjacency list directed/undirected graph with Dijkstra shortest path |
| **check** | 01.00.00 | [link](doc/check.en.md) | [source/04_algorithm](source/04_algorithm/) | Checksum suite: LRC, BCC, XOR parity, and arithmetic sum |
| **crc** | 01.00.00 | [link](doc/crc.en.md) | [source/04_algorithm](source/04_algorithm/) | Table-driven CRC algorithms: CRC-8, CRC-16, and CRC-32 |
| **encrypt** | 01.00.00 | [link](doc/encrypt.en.md) | [source/04_algorithm](source/04_algorithm/) | Cryptographic ciphers: AES-128/256, DES, Triple-DES, RSA, MD5 |
| **filter** | 01.01.00 | [link](doc/filter.en.md) | [source/04_algorithm](source/04_algorithm/) | Digital filters: 2nd-order Butterworth low-pass, clamping average, complementary (IMU attitude), Kalman, RC low-pass, median |
| **bpack** | 01.00.00 | [link](doc/bpack.en.md) | [source/04_algorithm](source/04_algorithm/) | Bitstream packing/unpacking and protocol codec supporting arbitrary bit-widths, Intel/Motorola endianness, and physical scaling |
| **base64** | 01.00.00 | [link](doc/base64.en.md) | [source/04_algorithm](source/04_algorithm/) | Standard & URL-safe Base64 encoder/decoder (RFC 4648) with 0-heap overhead |
| **compress** | 01.00.00 | [link](doc/compress.en.md) | [source/04_algorithm](source/04_algorithm/) | Multi-algorithm lossless compression suite (fast LZ4, PackBits RLE, sliding-window LZSS, envelope packaging) |
| **hash** | 01.00.00 | [link](doc/hash.en.md) | [source/04_algorithm](source/04_algorithm/) | Discrete hash algorithms: MurmurHash3, CityHash, FNV-1a, and classic hashes |
| **pid** | 01.00.00 | [link](doc/pid.en.md) | [source/04_algorithm](source/04_algorithm/) | Industrial-grade positional and incremental PID closed-loop controller |
| **search** | 01.00.00 | [link](doc/search.en.md) | [source/04_algorithm](source/04_algorithm/) | Search algorithms: binary search with bounds, KMP linear string matcher |
| **sort** | 01.00.00 | [link](doc/sort.en.md) | [source/04_algorithm](source/04_algorithm/) | Classic sorting routines: Quicksort, Heapsort, Mergesort, Insertion sort |
| **csv** | 01.00.00 | [link](doc/csv.en.md) | [source/05_parser](source/05_parser/) | RFC 4180 compliant CSV tabular parser and generator |
| **ini** | 01.00.00 | [link](doc/ini.en.md) | [source/05_parser](source/05_parser/) | INI configuration parser with Section / Key-Value read/write |
| **json** | 01.00.00 | [link](doc/json.en.md) | [source/05_parser](source/05_parser/) | Lightweight JSON DOM tree and streaming serializer |
| **nmea** | 01.00.00 | [link](doc/nmea.en.md) | [source/05_parser](source/05_parser/) | NMEA-0183 GNSS/GPS navigation parser (RMC/GGA/GSA/VTG/GSV with full constellation talker detection) |
| **protobuf** | 01.00.00 | [link](doc/protobuf.en.md) | [source/05_parser](source/05_parser/) | Google Protocol Buffers binary stream serializer & parser, 0-heap overhead |
| **txls** | 01.01.00 | [link](doc/txls.en.md) | [source/05_parser](source/05_parser/) | Tab-separated matrix table parser for rapid parameter calibration |
| **xml** | 01.00.00 | [link](doc/xml.en.md) | [source/05_parser](source/05_parser/) | Compact XML tag tree processor supporting attributes and CDATA |
| **yaml** | 00.01.00 | [link](doc/yaml.en.md) | [source/05_parser](source/05_parser/) | Pure C YAML indentation parser for nested mappings and sequences |
| **ramt** | 01.00.00 | [link](doc/ramt.en.md) | [source/06_performance](source/06_performance/) | RAM diagnostics with stack watermark detection and pool monitoring |
| **romt** | 01.00.00 | [link](doc/romt.en.md) | [source/06_performance](source/06_performance/) | Flash ROM static analyzer for section footprints (.text/.data/.bss) |
| **cant** | 00.01.00 | [link](doc/cant.en.md) | [source/06_performance](source/06_performance/) | Automotive CAN bus testing tool with frame injection and periodic filters |
| **slup** | 00.01.00 | [link](doc/slup.en.md) | [source/06_performance](source/06_performance/) | Simple Link Universal Protocol for streaming framing, SN, and 1024B RX queue |
| **cpul** | 01.00.00 | [link](doc/cpul.en.md) | [source/06_performance](source/06_performance/) | Real-time CPU utilization load analyzer with idle task sampling |
| **unitt** | 01.00.00 | [link](doc/unitt.en.md) | [source/06_performance](source/06_performance/) | Embedded automated unit testing framework with microsecond timing |
| **intl** | 01.01.00 | [link](doc/intl.en.md) | [source/07_math](source/07_math/) | Arbitrary-precision integer math (Knuth D, Karatsuba, C++ template `varch::intl`, `varch::uintl`) |
| **floatl** | 01.01.01 | [link](doc/floatl.en.md) | [source/07_math](source/07_math/) | IEEE-754 arbitrary-precision float math (bitstream extraction, Newton div, `varch::floatl`) |
| **flmath** | 01.00.00 | [link](doc/flmath.en.md) | [source/07_math](source/07_math/) | Big float transcendental math (trig, hyperbolic, exp, log, erf, activation) |
| **coroutine** | 00.02.00 | [link](doc/coroutine.en.md) | [source/08_coroutine](source/08_coroutine/) | Cooperative fiber coroutines with async IO scheduler, mutex, and channels |
---
## 🚀 Quick Start & Compilation
### 1. Prerequisites
- **Toolchain**: GCC or MinGW-W64 (supporting C99 and C++11)
- **Build Tool**: GNU Make 4.0+
- **Host Environments**: Linux, Windows (MSYS2 / MinGW / PowerShell)
### 2. Common Build Commands
#### ① Build Static Library (`libvarch.a`)
```bash
make lib
```
Output: `built/libvarch.a`. Required before building standalone targets or linking with external projects.
#### ② Build and Run Monolithic Console Application (`app`)
```bash
make app # Build main application
make run # Build and launch interactive terminal
```
In the interactive shell:
```text
varch > help
varch > intl -h
varch > crc -e
```
#### ③ Dual-Mode Standalone Module Testing (`make `)
Any module can be compiled into a standalone test executable:
```bash
make lib # Ensure static library is built
make intl # Builds standalone big int runner -> built/bin/intl (.exe)
make crc # Builds CRC test runner -> built/bin/crc (.exe)
make json # Builds JSON test runner -> built/bin/json (.exe)
# Run standalone test executable
./built/bin/intl -h
./built/bin/intl
```
#### ④ Test Modern C++11 Template Wrappers (`test_cpp`)
```bash
make test_cpp
```
Compiles `test/test_math_cpp.cpp` with `g++ -std=c++11` to validate `varch::intl`, `varch::uintl`, and `varch::floatl`.
#### ⑤ Clean Build Artifacts
```bash
make clean # Cleans built/obj and built/bin
```
---
## 🛠️ Installation
### Linux
```bash
sudo make install # Installs to /usr/include/varch and /usr/lib/libvarch.a
```
### Windows MinGW Custom Path
```bash
make install LIBP=D:/MinGW
```
### Uninstall
```bash
sudo make uninstall [LIBP=]
```
---
## 📄 License
Licensed under the **[GPL-2.0](LICENSE)** license. Contributions, discussions, and issues are warmly welcomed!
---
## 📬 Contact & Community
- **Repository**: [https://gitee.com/Lamdonn/varch](https://gitee.com/Lamdonn/varch)
- **Author Email**: [Lamdonn@163.com](mailto:Lamdonn@163.com)