### Install and test project
Source: https://github.com/eerimoq/asn1tools/blob/master/docs/index.md
Commands for setting up the development environment and running tests.
```text
pip install -r requirements.txt
```
```text
make test
```
--------------------------------
### Install asn1tools
Source: https://github.com/eerimoq/asn1tools/blob/master/docs/index.md
Install the asn1tools package using pip.
```python
pip install asn1tools
```
--------------------------------
### Start server and client
Source: https://github.com/eerimoq/asn1tools/blob/master/tests/js_source/README.rst
Launches the Python server in the background and starts the JavaScript client application.
```text
$ python3 server.py &
$ yarn start
```
--------------------------------
### Install and test dependencies
Source: https://github.com/eerimoq/asn1tools/blob/master/tests/js_source/README.rst
Use these commands to install project dependencies and execute the test suite.
```text
$ yarn install
$ yarn test
```
--------------------------------
### Start asn1tools shell
Source: https://github.com/eerimoq/asn1tools/blob/master/README.rst
Initiate the asn1tools interactive shell for compiling and converting data.
```bash
> asn1tools shell
Welcome to the asn1tools shell!
$ help
Commands:
compile
convert
exit
help
$ compile tests/files/foo.asn
$ convert Question 300e0201011609497320312b313d333f
question Question ::= {
id 1,
question "Is 1+1=3?"
}
$ compile --output-codec xer tests/files/foo.asn
$ convert Question 300e0201011609497320312b313d333f
1
Is 1+1=3?
$ compile -o uper tests/files/foo.asn
$ convert Question 300e0201011609497320312b313d333f
01010993cd03156c5eb37e
$ exit
>
```
--------------------------------
### Example Execution Output
Source: https://github.com/eerimoq/asn1tools/blob/master/examples/compact_extensions_uper/README.rst
This output shows the results of encoding and decoding operations using different versions of an ASN.1 schema. It highlights the byte sizes and decoded structures for various inputs.
```text
$ ./main.py
Encode V1:
Input: ('foo', {'b': 55, 'e': 'on', 'a': True, 'c': 3, 'd': False})
Output: 16ec (2 bytes)
Encode V2:
Input: ('foo', {'b': 55, 'e': 'on', 'a': True, 'c': 3, 'd': False})
Output: 16ec (2 bytes)
Input: ('foo', {'v2': {'b': True, 'a': -1}, 'b': 55, 'd': False, 'c': 3, 'e': 'on', 'a': True})
Output: 36ec3fc0 (4 bytes)
Input: ('bar', 3)
Output: 46 (1 bytes)
Encode V2 with extension markers:
Input: ('foo', {'b': 55, 'e': 'on', 'a': True, 'c': 3, 'd': False})
Output: 2dd8 (2 bytes)
Input: ('foo', {'b': 55, 'd': False, 'g': True, 'c': 3, 'e': 'on', 'a': True, 'f': -1})
Output: 6dd80204ff00 (6 bytes)
Input: ('bar', 3)
Output: 800118 (3 bytes)
Decode V1 with V1:
Input: 16ec
Output: ('foo', {'b': 55, 'e': 'on', 'a': True, 'c': 3, 'd': False})
Decode V1 with V2:
Input: 16ec
Output: ('foo', {'b': 55, 'e': 'on', 'a': True, 'c': 3, 'd': False})
Decode V2 with V1:
Input: 16ec
Output: ('foo', {'b': 55, 'e': 'on', 'a': True, 'c': 3, 'd': False})
Input: 36ec3fc0
Output: ('foo', {'b': 55, 'extension': None, 'd': False, 'c': 3, 'e': 'on', 'a': True})
Input: 46
Output: ('extension1', None)
Decode V2 with V2:
Input: 16ec
Output: ('foo', {'b': 55, 'e': 'on', 'a': True, 'c': 3, 'd': False})
Input: 36ec3fc0
Output: ('foo', {'v2': {'b': True, 'a': -1}, 'b': 55, 'd': False, 'c': 3, 'e': 'on', 'a': True})
Input: 46
Output: ('bar', 3)
$
```
--------------------------------
### Start Interactive asn1tools Shell
Source: https://context7.com/eerimoq/asn1tools/llms.txt
Launch an interactive shell for compiling ASN.1 specifications and converting data. Use commands like 'compile' and 'convert' within the shell.
```bash
asn1tools shell
```
```bash
# Welcome to the asn1tools shell!
#
# $ compile tests/files/foo.asn
# $ convert Question 300e0201011609497320312b313d333f
# question Question ::=
# id 1,
# question "Is 1+1=3?"
# }
# $ compile --output-codec xer tests/files/foo.asn
# $ convert Question 300e0201011609497320312b313d333f
#
# 1
# Is 1+1=3?
#
# $ exit
```
--------------------------------
### Convert encoded data formats
Source: https://github.com/eerimoq/asn1tools/blob/master/docs/index.md
Examples of converting encoded ASN.1 data between different formats using the convert subcommand.
```text
> asn1tools convert tests/files/foo.asn Question 300e0201011609497320312b313d333f
question Question ::= {
id 1,
question "Is 1+1=3?"
}
>
```
```text
> asn1tools convert -i uper -o xer tests/files/foo.asn Question 01010993cd03156c5eb37e
1
Is 1+1=3?
>
```
```text
> asn1tools convert -i uper -o jer tests/files/foo.asn Question 01010993cd03156c5eb37e
{
"id": 1,
"question": "Is 1+1=3?"
}
>
```
--------------------------------
### Get Message Length from Header using Specification.decode_length
Source: https://context7.com/eerimoq/asn1tools/llms.txt
Decodes only the length from BER/DER encoded data without fully decoding the content. Useful for framing and buffering, returns None if not enough data is available.
```python
import asn1tools
foo = asn1tools.compile_files('foo.asn')
# Get message length from partial data (BER/DER only)
partial_data = b'\x30\x0e\x02\x01\x01'
length = foo.decode_length(partial_data)
print(f"Full message length: {length}") # 16
# Returns None if not enough data to determine length
insufficient_data = b'\x30'
length = foo.decode_length(insufficient_data)
if length is None:
print("Need more data to determine length")
```
--------------------------------
### Convert with cache
Source: https://github.com/eerimoq/asn1tools/blob/master/docs/index.md
Use the --cache-dir option to speed up repeated conversion tasks.
```text
> time asn1tools convert --cache-dir my_cache -i uper tests/files/3gpp/rrc_8_6_0.asn PCCH-Message 28
pcch-message PCCH-Message ::= {
message c1 : paging : {
systemInfoModification true,
nonCriticalExtension {
}
}
}
real 0m2.090s
user 0m1.977s
sys 0m0.032s
> time asn1tools convert --cache-dir my_cache -i uper tests/files/3gpp/rrc_8_6_0.asn PCCH-Message 28
pcch-message PCCH-Message ::= {
message c1 : paging : {
systemInfoModification true,
nonCriticalExtension {
}
}
}
real 0m0.276s
user 0m0.197s
sys 0m0.026s
>
```
--------------------------------
### Use Caching for Conversions
Source: https://context7.com/eerimoq/asn1tools/llms.txt
Enable caching for faster repeated conversions by specifying a cache directory using the '--cache-dir' option with the 'convert' command.
```bash
asn1tools convert --cache-dir my_cache -i uper foo.asn Message 28
```
--------------------------------
### Compile ASN.1 and encode/decode with PER
Source: https://github.com/eerimoq/asn1tools/blob/master/README.rst
Compile an ASN.1 file and use it to encode and decode messages with the PER codec.
```python
>>> import asn1tools
>>> foo = asn1tools.compile_files('tests/files/foo.asn', 'per')
>>> encoded = foo.encode('Question', {'id': 1, 'question': 'Is 1+1=3?'})
>>> encoded
bytearray(b'\x01\x01\tIs 1+1=3?')
>>> foo.decode('Question', encoded)
{'id': 1, 'question': 'Is 1+1=3?'}
```
--------------------------------
### asn1tools Shell - Convert with XER
Source: https://github.com/eerimoq/asn1tools/blob/master/docs/index.md
Convert data to XER format using the asn1tools shell.
```text
$ convert Question 300e0201011609497320312b313d333f
1
Is 1+1=3?
```
--------------------------------
### asn1tools Runtime Memory Usage
Source: https://github.com/eerimoq/asn1tools/blob/master/examples/benchmarks/c_source/README.rst
Shows runtime memory usage for asn1tools captured with Valgrind Massif, detailing heap and stack allocations.
```text
--------------------------------------------------------------------------------
n time(B) total(B) useful-heap(B) extra-heap(B) stacks(B)
--------------------------------------------------------------------------------
52 209,480 1,192 0 0 1,192
53 211,936 1,648 0 0 1,648
54 214,464 1,744 0 0 1,744
55 216,904 1,192 0 0 1,192
56 219,328 320 0 0 320
57 221,872 800 0 0 800
58 224,296 936 0 0 936
59 226,720 912 0 0 912
```
--------------------------------
### Generate C source code
Source: https://github.com/eerimoq/asn1tools/blob/master/docs/index.md
Commands to generate C source files from an ASN.1 specification file.
```text
> asn1tools generate_c_source --namespace oer tests/files/c_source/c_source.asn
Successfully generated oer.h and oer.c.
```
```text
> asn1tools generate_c_source --codec uper --namespace uper tests/files/c_source/c_source.asn
Successfully generated uper.h and uper.c.
```
```text
> asn1tools generate_c_source --namespace oer --generate-fuzzer tests/files/c_source/c_source.asn
Successfully generated oer.h and oer.c.
Successfully generated oer_fuzzer.c and oer_fuzzer.mk.
Run "make -f oer_fuzzer.mk" to build and run the fuzzer. Requires a
recent version of clang.
```
--------------------------------
### Compile and Encode/Decode with PER
Source: https://github.com/eerimoq/asn1tools/blob/master/docs/index.md
Compile an ASN.1 specification and then encode and decode a message using the PER codec.
```python
>>> import asn1tools
>>> foo = asn1tools.compile_files('tests/files/foo.asn', 'per')
>>> encoded = foo.encode('Question', {'id': 1, 'question': 'Is 1+1=3?'})
>>> encoded
bytearray(b'\x01\x01\x09Is 1+1=3?')
>>> foo.decode('Question', encoded)
{'id': 1, 'question': 'Is 1+1=3?'}
```
--------------------------------
### asn1tools Shell - Help Command
Source: https://github.com/eerimoq/asn1tools/blob/master/docs/index.md
Display available commands in the asn1tools shell.
```text
> asn1tools shell
Welcome to the asn1tools shell!
$ help
Commands:
compile
convert
exit
help
```
--------------------------------
### asn1tools Shell - Convert with UPER
Source: https://github.com/eerimoq/asn1tools/blob/master/docs/index.md
Convert data to UPER format using the asn1tools shell.
```text
$ convert Question 300e0201011609497320312b313d333f
01010993cd03156c5eb37e
```
--------------------------------
### Generate C Source Code for ASN.1
Source: https://context7.com/eerimoq/asn1tools/llms.txt
Use 'generate_c_source' to create C header and source files for encoding/decoding ASN.1 types. Specify the namespace and optionally the codec (e.g., OER, UPER) and whether to generate fuzzer code.
```bash
asn1tools generate_c_source --namespace myprotocol protocol.asn
```
```bash
asn1tools generate_c_source --codec uper --namespace myprotocol protocol.asn
```
```bash
asn1tools generate_c_source --namespace myprotocol --generate-fuzzer protocol.asn
```
--------------------------------
### asn1tools Executable Size
Source: https://github.com/eerimoq/asn1tools/blob/master/examples/benchmarks/c_source/README.rst
Displays the executable size statistics for asn1tools, including text, data, bss, decimal, and hexadecimal sizes.
```text
text data bss dec hex filename
5553 560 8 6121 17e9 main
```
--------------------------------
### asn1tools Shell - Compile with XER Output
Source: https://github.com/eerimoq/asn1tools/blob/master/docs/index.md
Compile an ASN.1 specification file with XER as the output codec using the asn1tools shell.
```text
$ compile --output-codec xer tests/files/foo.asn
```
--------------------------------
### Generate C Source Code using asn1tools.source.c.generate
Source: https://context7.com/eerimoq/asn1tools/llms.txt
Generates C header and source files for encoding/decoding ASN.1 types using OER or UPER codecs. Designed for no dynamic memory allocation.
```python
import asn1tools
from asn1tools.source import c
# Compile the specification
compiled = asn1tools.compile_files('protocol.asn', 'oer')
# Generate C source code
header, source, fuzzer_source, fuzzer_makefile = c.generate(
compiled,
codec='oer',
namespace='protocol',
header_name='protocol.h',
source_name='protocol.c',
fuzzer_source_name='protocol_fuzzer.c'
)
# Write the generated files
with open('protocol.h', 'w') as f:
f.write(header)
with open('protocol.c', 'w') as f:
f.write(source)
# The generated C code can be used like:
# protocol_message_t msg;
# ssize_t size = protocol_message_encode(buffer, sizeof(buffer), &msg);
# ssize_t result = protocol_message_decode(&msg, buffer, size);
```
--------------------------------
### Compile and Encode/Decode with BER
Source: https://github.com/eerimoq/asn1tools/blob/master/docs/index.md
Compile an ASN.1 specification and then encode and decode a message using the default BER codec.
```python
>>> import asn1tools
>>> foo = asn1tools.compile_files('tests/files/foo.asn')
>>> encoded = foo.encode('Question', {'id': 1, 'question': 'Is 1+1=3?'})
>>> encoded
bytearray(b'0\x0e\x02\x01\x01\x16\x09Is 1+1=3?')
>>> foo.decode('Question', encoded)
{'id': 1, 'question': 'Is 1+1=3?'}
```
--------------------------------
### asn1tools Shell - Compile with UPER Output
Source: https://github.com/eerimoq/asn1tools/blob/master/docs/index.md
Compile an ASN.1 specification file with UPER as the output codec using the asn1tools shell.
```text
$ compile -o uper tests/files/foo.asn
```
--------------------------------
### asn1tools Execution Time
Source: https://github.com/eerimoq/asn1tools/blob/master/examples/benchmarks/c_source/README.rst
Shows the execution time in seconds for asn1tools with -O3 and -Os optimizations when encoding and decoding a PDU 1,000,000 times.
```text
+-----------+--------------+--------------------+
| Tool | Optimization | Exexution time [s] |
+===========+==============+====================+
| asn1tools | -O3 | 1.229 |
+-----------+--------------+--------------------+
| asn1tools | -Os | 2.987 |
+-----------+--------------+--------------------+
```
--------------------------------
### Compare ASN.1 Codec Performance
Source: https://context7.com/eerimoq/asn1tools/llms.txt
Iterate through various ASN.1 codecs ('ber', 'der', 'per', 'uper', 'oer', 'jer', 'xer', 'gser') to encode the same data and compare the resulting size and format. This helps in choosing the most efficient codec for specific needs.
```python
import asn1tools
import binascii
# Sample ASN.1 schema
schema = '''
Protocol DEFINITIONS ::=
Message ::=
SEQUENCE {
id INTEGER (0..255),
data OCTET STRING (SIZE(1..100))
}
END
'''
data = {'id': 42, 'data': b'Hello, ASN.1!'}
# Compare different codecs
codecs = ['ber', 'der', 'per', 'uper', 'oer', 'jer', 'xer', 'gser']
for codec in codecs:
spec = asn1tools.compile_string(schema, codec)
try:
encoded = spec.encode('Message', data)
if isinstance(encoded, bytes):
print(f"{codec.upper():5}: {len(encoded):3} bytes - {binascii.hexlify(encoded).decode()}")
else:
print(f"{codec.upper():5}: {len(encoded):3} chars - {encoded[:50]}...")
except Exception as e:
print(f"{codec.upper():5}: Error - {e}")
# Example output:
# BER : 19 bytes - 30110201021a0d48656c6c6f2c2041534e2e3121
# DER : 19 bytes - 30110201021a0d48656c6c6f2c2041534e2e3121
# PER : 15 bytes - 2a0d48656c6c6f2c2041534e2e3121
# UPER : 15 bytes - 150348656c6c6f2c2041534e2e3121
# OER : 16 bytes - 2a0d48656c6c6f2c2041534e2e3121
# JER : 35 chars - {"id": 42, "data": "SGVsbG8sIEFTTi4...
# XER : 80 chars - 4248656c6c6f...
# GSER : 45 chars - message Message ::= { id 42, data '...
```
--------------------------------
### asn1tools Shell - Compile Command
Source: https://github.com/eerimoq/asn1tools/blob/master/docs/index.md
Compile an ASN.1 specification file using the asn1tools shell.
```text
$ compile tests/files/foo.asn
```
--------------------------------
### Compile ASN.1 Specification Files
Source: https://context7.com/eerimoq/asn1tools/llms.txt
Use compile_files to load and compile one or more ASN.1 schema files. Specify the codec, enable caching, or use numeric enums for different use cases.
```python
import asn1tools
# Basic compilation with default BER codec
foo = asn1tools.compile_files('foo.asn')
# Compile with specific codec (PER)
foo_per = asn1tools.compile_files('foo.asn', 'per')
# Compile multiple files with UPER codec
spec = asn1tools.compile_files(['module1.asn', 'module2.asn'], 'uper')
# Compile with caching for faster subsequent loads
foo_cached = asn1tools.compile_files('foo.asn', cache_dir='my_cache')
# Compile with numeric enumeration values instead of strings
foo_numeric = asn1tools.compile_files('foo.asn', numeric_enums=True)
# Available codecs: 'ber', 'der', 'gser', 'jer', 'oer', 'per', 'uper', 'xer'
```
--------------------------------
### Access Module-organized Types using Specification.modules
Source: https://context7.com/eerimoq/asn1tools/llms.txt
Access types organized by their source module. Useful when type names are duplicated across modules, allowing access to specific types from specific modules.
```python
import asn1tools
spec = asn1tools.compile_files(['module1.asn', 'module2.asn'])
# Access types by module
for module_name, types in spec.modules.items():
print(f"Module: {module_name}")
for type_name in types:
print(f" - {type_name}")
# Access a specific type from a specific module
message_type = spec.modules['MyModule']['Message']
encoded = message_type.encode({'field': 'value'})
```
--------------------------------
### Convert UPER to XER (XML)
Source: https://context7.com/eerimoq/asn1tools/llms.txt
Use the 'convert' command with '-i uper' and '-o xer' to transform UPER encoded data to XER (XML) format. Specify the ASN.1 schema file, type name, and the UPER data.
```bash
asn1tools convert -i uper -o xer foo.asn Question 01010993cd03156c5eb37e
```
--------------------------------
### Convert UPER to XER using asn1tools CLI
Source: https://github.com/eerimoq/asn1tools/blob/master/README.rst
Convert an ASN.1 encoded message from UPER to XER (XML) format using the command line tool.
```bash
> asn1tools convert -i uper -o xer tests/files/foo.asn Question 01010993cd03156c5eb37e
1
Is 1+1=3?
>
```
--------------------------------
### Parse ASN.1 to Python
Source: https://context7.com/eerimoq/asn1tools/llms.txt
Use the 'parse' command to convert ASN.1 specifications into Python dictionaries, which can then be used for faster subsequent loads and conversions.
```bash
asn1tools parse protocol.asn protocol.py
```
```bash
asn1tools convert protocol.py Message 300e0201011609497320312b313d333f
```
--------------------------------
### asn1c Execution Time
Source: https://github.com/eerimoq/asn1tools/blob/master/examples/benchmarks/c_source/README.rst
Shows the execution time in seconds for asn1c with -O3 and -Os optimizations when encoding and decoding a PDU 1,000,000 times.
```text
+-----------+--------------+--------------------+
| Tool | Optimization | Exexution time [s] |
+===========+==============+====================+
| asn1c | -O3 | 10.902 |
+-----------+--------------+--------------------+
| asn1c | -Os | 12.569 |
+-----------+--------------+--------------------+
```
--------------------------------
### Parse ASN.1 to Dictionary using parse_files
Source: https://context7.com/eerimoq/asn1tools/llms.txt
Parses ASN.1 specification files into a Python dictionary representation without compiling. Useful for inspection, modification, or custom processing.
```python
import asn1tools
from pprint import pprint
# Parse a single file
parsed = asn1tools.parse_files('foo.asn')
pprint(parsed)
# Parse multiple files
parsed = asn1tools.parse_files(['module1.asn', 'module2.asn'])
# Access module and type information
for module_name, module in parsed.items():
print(f"Module: {module_name}")
for type_name, type_def in module['types'].items():
print(f" Type: {type_name} = {type_def['type']}")
```
--------------------------------
### asn1c Executable Size
Source: https://github.com/eerimoq/asn1tools/blob/master/examples/benchmarks/c_source/README.rst
Displays the executable size statistics for asn1c, including text, data, bss, decimal, and hexadecimal sizes.
```text
text data bss dec hex filename
63733 4904 80 68717 10c6d main
```
--------------------------------
### asn1tools.source.c.generate
Source: https://context7.com/eerimoq/asn1tools/llms.txt
Generates C header and source files for encoding/decoding ASN.1 types.
```APIDOC
## asn1tools.source.c.generate
### Description
Generates C header and source files for encoding/decoding ASN.1 types using OER or UPER codecs, with no dynamic memory allocation.
### Response
- **header** (str) - The generated C header file content.
- **source** (str) - The generated C source file content.
- **fuzzer_source** (str) - The generated fuzzer source code.
- **fuzzer_makefile** (str) - The generated makefile for the fuzzer.
```
--------------------------------
### Convert ASN.1 Encoded Data using asn1tools convert CLI
Source: https://context7.com/eerimoq/asn1tools/llms.txt
Converts ASN.1 encoded data between different encoding rules directly from the command line. Requires the ASN.1 specification file, type name, and encoded data.
```bash
# Convert BER-encoded data to human-readable GSER
asn1tools convert foo.asn Question 300e0201011609497320312b313d333f
# Output:
# question Question ::=
# id 1,
# question "Is 1+1=3?"
```
--------------------------------
### asn1scc Executable Size
Source: https://github.com/eerimoq/asn1tools/blob/master/examples/benchmarks/c_source/README.rst
Displays the executable size statistics for asn1scc, including text, data, bss, decimal, and hexadecimal sizes.
```text
text data bss dec hex filename
12073 560 8 12641 3161 main
```
--------------------------------
### Convert UPER to JER (JSON)
Source: https://context7.com/eerimoq/asn1tools/llms.txt
Use the 'convert' command with '-i uper' and '-o jer' to transform UPER encoded data to JER (JSON) format. Specify the ASN.1 schema file, type name, and the UPER data.
```bash
asn1tools convert -i uper -o jer foo.asn Question 01010993cd03156c5eb37e
```
--------------------------------
### parse_files
Source: https://context7.com/eerimoq/asn1tools/llms.txt
Parses ASN.1 specification files into a Python dictionary representation.
```APIDOC
## parse_files
### Description
Parses ASN.1 specification files into a Python dictionary representation without compiling. Useful for inspection, modification, or custom processing.
### Response
- **parsed** (dict) - A dictionary containing the module and type definitions extracted from the files.
```
--------------------------------
### Parse ASN.1 specification
Source: https://github.com/eerimoq/asn1tools/blob/master/docs/index.md
Pre-parse an ASN.1 specification into a Python dictionary to accelerate subsequent conversion operations.
```text
> asn1tools parse tests/files/foo.asn foo.py
> asn1tools convert foo.py Question 300e0201011609497320312b313d333f
question Question ::= {
id 1,
question "Is 1+1=3?"
}
>
```
--------------------------------
### asn1scc Execution Time
Source: https://github.com/eerimoq/asn1tools/blob/master/examples/benchmarks/c_source/README.rst
Shows the execution time in seconds for asn1scc with -O3 and -Os optimizations when encoding and decoding a PDU 1,000,000 times.
```text
+-----------+--------------+--------------------+
| Tool | Optimization | Exexution time [s] |
+===========+==============+====================+
| asn1scc | -O3 | 4.023 |
+-----------+--------------+--------------------+
| asn1scc | -Os | 6.166 |
+-----------+--------------+--------------------+
```
--------------------------------
### asn1tools Shell - Convert with BER to GSER
Source: https://github.com/eerimoq/asn1tools/blob/master/docs/index.md
Convert data from BER to GSER format using the asn1tools shell.
```text
$ convert Question 300e0201011609497320312b313d333f
question Question ::=
id 1,
question "Is 1+1=3?"
```
--------------------------------
### asn1tools Source Code Statistics
Source: https://github.com/eerimoq/asn1tools/blob/master/examples/benchmarks/c_source/README.rst
Presents source code statistics for asn1tools, detailing lines of code, comments, and blank lines per language.
```text
-------------------------------------------------------------------------------
Language files blank comment code
-------------------------------------------------------------------------------
C 1 178 28 670
C/C++ Header 1 36 196 162
-------------------------------------------------------------------------------
SUM: 2 214 224 832
-------------------------------------------------------------------------------
```
--------------------------------
### asn1tools Shell - Exit Command
Source: https://github.com/eerimoq/asn1tools/blob/master/docs/index.md
Exit the asn1tools shell.
```text
$ exit
>
```
--------------------------------
### Compile ASN.1 from String
Source: https://context7.com/eerimoq/asn1tools/llms.txt
Use compile_string to compile an ASN.1 schema directly from a string. This is useful for dynamic schema definitions or when the schema is embedded.
```python
import asn1tools
asn1_schema = '''
MyProtocol DEFINITIONS ::= BEGIN
Message ::= SEQUENCE {
id INTEGER,
payload OCTET STRING
}
Status ::= ENUMERATED {
ok(0),
error(1),
pending(2)
}
END
'''
spec = asn1tools.compile_string(asn1_schema)
# Encode a message
encoded = spec.encode('Message', {'id': 42, 'payload': b'\x01\x02\x03'})
# Decode the message
decoded = spec.decode('Message', encoded)
print(decoded) # {'id': 42, 'payload': b'\x01\x02\x03'}
```
--------------------------------
### ASN.1 Specification Compilation
Source: https://context7.com/eerimoq/asn1tools/llms.txt
Functions to compile ASN.1 specifications from files, strings, or dictionaries.
```APIDOC
## ASN.1 Specification Compilation
This section covers the primary functions for compiling ASN.1 specifications into usable Python objects.
### `compile_files(files, codec='ber', cache_dir=None, numeric_enums=False)`
Compiles one or more ASN.1 specification files into a Specification object.
**Parameters**
- **files** (str or list[str]) - Path(s) to the ASN.1 specification file(s).
- **codec** (str) - The ASN.1 encoding rule to use (e.g., 'ber', 'per', 'xer'). Defaults to 'ber'.
- **cache_dir** (str, optional) - Directory to cache compiled specifications for faster loading.
- **numeric_enums** (bool) - If True, enumeration values will be integers; otherwise, strings. Defaults to False.
**Example**
```python
import asn1tools
spec_ber = asn1tools.compile_files('my_spec.asn')
spec_per = asn1tools.compile_files(['mod1.asn', 'mod2.asn'], 'per', cache_dir='my_cache')
```
### `compile_string(asn1_string, codec='ber', numeric_enums=False)`
Compiles an ASN.1 specification provided as a string.
**Parameters**
- **asn1_string** (str) - The ASN.1 specification as a string.
- **codec** (str) - The ASN.1 encoding rule to use. Defaults to 'ber'.
- **numeric_enums** (bool) - If True, enumeration values will be integers; otherwise, strings. Defaults to False.
**Example**
```python
import asn1tools
asn1_schema = """
MyProtocol DEFINITIONS ::= BEGIN
Data ::= SEQUENCE { value INTEGER }
END
"""
spec = asn1tools.compile_string(asn1_schema)
```
### `compile_dict(parsed_dict, codec='ber', any_defined_by_choices=None)`
Compiles an ASN.1 specification from a pre-parsed dictionary.
**Parameters**
- **parsed_dict** (dict) - The parsed ASN.1 specification, typically from `parse_files` or `parse_string`.
- **codec** (str) - The ASN.1 encoding rule to use. Defaults to 'ber'.
- **any_defined_by_choices** (dict, optional) - Dictionary to specify types for `ANY DEFINED BY` constructs.
**Example**
```python
import asn1tools
parsed = asn1tools.parse_files('protocol.asn')
spec = asn1tools.compile_dict(parsed, 'oer')
```
**Available codecs**: 'ber', 'der', 'gser', 'jer', 'oer', 'per', 'uper', 'xer'
```
--------------------------------
### Convert UPER to JER using asn1tools CLI
Source: https://github.com/eerimoq/asn1tools/blob/master/README.rst
Convert an ASN.1 encoded message from UPER to JER (JSON) format using the command line tool.
```bash
> asn1tools convert -i uper -o jer tests/files/foo.asn Question 01010993cd03156c5eb37e
{
"id": 1,
"question": "Is 1+1=3?"
}
>
```
--------------------------------
### Convert encoded data from standard input
Source: https://github.com/eerimoq/asn1tools/blob/master/docs/index.md
Process multiple encoded inputs from standard input using the convert subcommand.
```text
> cat encoded.txt
2018-02-24 11:22:09
300e0201011609497320312b313d333f
2018-02-24 11:24:15
300e0201021609497320322b323d353f
> cat encoded.txt | asn1tools convert tests/files/foo.asn Question -
2018-02-24 11:22:09
question Question ::= {
id 1,
question "Is 1+1=3?"
}
2018-02-24 11:24:15
question Question ::= {
id 2,
question "Is 2+2=5?"
}
>
```
--------------------------------
### Configure numeric enumeration values
Source: https://github.com/eerimoq/asn1tools/blob/master/docs/index.md
Use this compilation setting to represent ENUMERATED types as integers instead of strings.
```python
numeric_enums=True
```
--------------------------------
### Compile Pre-parsed ASN.1 Dictionary
Source: https://context7.com/eerimoq/asn1tools/llms.txt
Use compile_dict to compile an ASN.1 specification from a pre-parsed dictionary. This allows for inspection or modification before compilation and supports compiling 'ANY DEFINED BY' choices.
```python
import asn1tools
# Parse and then compile separately (useful for inspection/modification)
parsed = asn1tools.parse_files('protocol.asn')
spec = asn1tools.compile_dict(parsed, 'ber')
# Compile with ANY DEFINED BY choices for legacy protocols
any_defined_by_choices = {
('Module', 'Message', 'content'): {
1: 'OCTET STRING',
2: 'INTEGER'
}
}
spec = asn1tools.compile_dict(parsed, 'ber', any_defined_by_choices)
```
--------------------------------
### Convert BER to GSER using asn1tools CLI
Source: https://github.com/eerimoq/asn1tools/blob/master/README.rst
Convert an ASN.1 encoded message from BER to GSER format using the command line tool.
```bash
> asn1tools convert tests/files/foo.asn Question 300e0201011609497320312b313d333f
question Question ::= {
id 1,
question "Is 1+1=3?"
}
>
```
--------------------------------
### asn1c Source Code Statistics
Source: https://github.com/eerimoq/asn1tools/blob/master/examples/benchmarks/c_source/README.rst
Presents source code statistics for asn1c, detailing lines of code, comments, and blank lines per language.
```text
-------------------------------------------------------------------------------
Language files blank comment code
-------------------------------------------------------------------------------
C 34 1421 1822 8834
C/C++ Header 38 398 762 1325
-------------------------------------------------------------------------------
SUM: 72 1819 2584 10159
-------------------------------------------------------------------------------
```
--------------------------------
### Parse ASN.1 String to Dictionary using parse_string
Source: https://context7.com/eerimoq/asn1tools/llms.txt
Parses an ASN.1 specification string into a dictionary representation. The output dictionary contains the parsed structure of the ASN.1 definition.
```python
import asn1tools
asn1_text = '''
Example DEFINITIONS ::= BEGIN
Point ::= SEQUENCE {
x INTEGER,
y INTEGER
}
END
'''
parsed = asn1tools.parse_string(asn1_text)
print(parsed['Example']['types']['Point'])
# {'type': 'SEQUENCE', 'members': [{'name': 'x', 'type': 'INTEGER'}, ...]}}
```
--------------------------------
### Handle ASN.1 ParseError
Source: https://context7.com/eerimoq/asn1tools/llms.txt
Catch 'ParseError' exceptions when the ASN.1 syntax is invalid. This is useful for validating ASN.1 strings before compilation.
```python
import asn1tools
try:
asn1tools.parse_string('Invalid ASN.1 syntax')
except asn1tools.ParseError as e:
print(f"Parse error: {e}")
```
--------------------------------
### asn1scc Source Code Statistics
Source: https://github.com/eerimoq/asn1tools/blob/master/examples/benchmarks/c_source/README.rst
Presents source code statistics for asn1scc, detailing lines of code, comments, and blank lines per language.
```text
-------------------------------------------------------------------------------
Language files blank comment code
-------------------------------------------------------------------------------
C 4 697 126 3020
C/C++ Header 2 176 28 529
-------------------------------------------------------------------------------
SUM: 6 873 154 3549
-------------------------------------------------------------------------------
```
--------------------------------
### Handle ASN.1 DecodeError
Source: https://context7.com/eerimoq/asn1tools/llms.txt
Catch 'DecodeError' exceptions that occur during decoding, such as when the provided data is malformed or does not match the expected type.
```python
import asn1tools
foo = asn1tools.compile_files('foo.asn')
try:
foo.decode('Question', b'\x00\x00\x00')
except asn1tools.DecodeError as e:
print(f"Decode error: {e}")
```
--------------------------------
### Decode Bytes to Data
Source: https://context7.com/eerimoq/asn1tools/llms.txt
The decode method converts bytes back into Python data structures using the compiled ASN.1 schema. It can perform constraint validation and handle various decoding errors.
```python
import asn1tools
foo = asn1tools.compile_files('foo.asn')
# Basic decoding
encoded_data = b'0\x0e\x02\x01\x01\x16\x09Is 1+1=3?'
decoded = foo.decode('Question', encoded_data)
print(decoded) # {'id': 1, 'question': 'Is 1+1=3?'}
# Decode with constraint validation
try:
decoded = foo.decode('Question', encoded_data, check_constraints=True)
except asn1tools.ConstraintsError as e:
print(f"Constraint violation: {e}")
# Handle decode errors
try:
decoded = foo.decode('Question', b'\x00\x00')
except asn1tools.DecodeError as e:
print(f"Decode error: {e}")
```
--------------------------------
### Specification.decode - Decode Data
Source: https://context7.com/eerimoq/asn1tools/llms.txt
Decodes ASN.1 byte sequences into Python data structures.
```APIDOC
## Specification.decode - Decode Data
Decodes ASN.1 byte sequences back into Python data structures according to a compiled specification.
### Method
`Specification.decode(type_name, data, check_constraints=False)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **type_name** (str) - The name of the ASN.1 type to decode.
- **data** (bytes) - The ASN.1 encoded byte sequence.
- **check_constraints** (bool) - Whether to validate against ASN.1 constraints after decoding. Defaults to False.
### Request Example
```python
import asn1tools
spec = asn1tools.compile_files('my_spec.asn')
encoded_data = b'...' # Assume this is valid ASN.1 encoded data
# Basic decoding
decoded_data = spec.decode('MyType', encoded_data)
print(decoded_data)
# Decoding with constraint validation
try:
spec.decode('MyType', encoded_data, check_constraints=True)
except asn1tools.ConstraintsError as e:
print(f"Constraint error: {e}")
```
### Response
#### Success Response (dict or value)
- **decoded_data** (dict or value) - The decoded Python data structure.
#### Response Example
```json
{
"example": {
"id": 1,
"name": "example"
}
}
```
#### Error Response
- **asn1tools.ConstraintsError**: If `check_constraints` is True and constraints are violated.
- **asn1tools.DecodeError**: If the data is malformed or cannot be decoded according to the specification.
```
--------------------------------
### Specification.encode - Encode Data
Source: https://context7.com/eerimoq/asn1tools/llms.txt
Encodes Python data structures into ASN.1 byte sequences.
```APIDOC
## Specification.encode - Encode Data
Encodes Python data structures into ASN.1 byte sequences according to a compiled specification.
### Method
`Specification.encode(type_name, data, check_types=True, check_constraints=False, indent=None)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **type_name** (str) - The name of the ASN.1 type to encode.
- **data** (dict or value) - The Python data to encode.
- **check_types** (bool) - Whether to perform type checking. Defaults to True.
- **check_constraints** (bool) - Whether to validate against ASN.1 constraints. Defaults to False.
- **indent** (int, optional) - Number of spaces for indentation, used for human-readable formats (GSER, XER, JER).
### Request Example
```python
import asn1tools
spec = asn1tools.compile_files('my_spec.asn')
# Basic encoding
my_data = {'id': 1, 'name': 'example'}
encoded_bytes = spec.encode('MyType', my_data)
# Encoding with constraint validation
try:
spec.encode('MyType', invalid_data, check_constraints=True)
except asn1tools.ConstraintsError as e:
print(f"Constraint error: {e}")
# Encoding CHOICE types (as tuple: ('choice_name', value))
choice_encoded = spec.encode('MyChoice', ('tag', 'some_value'))
# Encoding for human-readable formats
spec_gser = asn1tools.compile_files('my_spec.asn', 'gser')
encoded_gser = spec_gser.encode('MyType', my_data, indent=4)
```
### Response
#### Success Response (bytes)
- **encoded_bytes** (bytes) - The ASN.1 encoded data.
#### Response Example
```json
{
"example": "bytearray(b'...')"
}
```
#### Error Response
- **asn1tools.ConstraintsError**: If `check_constraints` is True and constraints are violated.
- **asn1tools.EncodeError**: If data cannot be encoded due to type mismatches or other encoding issues.
```
--------------------------------
### Access Compiled Types using Specification.types
Source: https://context7.com/eerimoq/asn1tools/llms.txt
Access the dictionary of all unique compiled types for direct type-level operations. Allows encoding/decoding directly using the type object.
```python
import asn1tools
foo = asn1tools.compile_files('foo.asn')
# List all available types
print(foo.types.keys())
# Access a specific type directly
question_type = foo.types['Question']
print(question_type) # Sequence(Question, [Integer(id), IA5String(question)])
# Encode/decode using type directly
encoded = question_type.encode({'id': 1, 'question': 'Test?'})
decoded = question_type.decode(encoded)
```
--------------------------------
### Handle ASN.1 CompileError
Source: https://context7.com/eerimoq/asn1tools/llms.txt
Catch 'CompileError' exceptions that occur during the compilation of ASN.1 specifications, such as when an invalid codec is specified.
```python
import asn1tools
try:
spec = asn1tools.compile_string('Bad DEFINITIONS ::= BEGIN END', 'invalid_codec')
except asn1tools.CompileError as e:
print(f"Compile error: {e}")
```
--------------------------------
### Decode with Length Information using Specification.decode_with_length
Source: https://context7.com/eerimoq/asn1tools/llms.txt
Decodes ASN.1 data and returns the number of bytes consumed. Useful for processing streams or concatenated messages, especially with indefinite-length BER.
```python
import asn1tools
foo = asn1tools.compile_files('foo.asn')
# Decode and get consumed length (useful for indefinite-length BER)
data = b'0\x0e\x02\x01\x01\x16\x09Is 1+1=3?'
decoded, length = foo.decode_with_length('Question', data)
print(f"Decoded: {decoded}")
print(f"Bytes consumed: {length}") # 16
# Process multiple concatenated messages
stream = data + data # Two messages concatenated
offset = 0
messages = []
while offset < len(stream):
msg, consumed = foo.decode_with_length('Question', stream[offset:])
messages.append(msg)
offset += consumed
```
--------------------------------
### Specification.decode_with_length
Source: https://context7.com/eerimoq/asn1tools/llms.txt
Decodes ASN.1 data and returns the number of bytes consumed, facilitating stream processing.
```APIDOC
## Specification.decode_with_length
### Description
Decodes data and also returns the number of bytes consumed, useful for processing streams or concatenated messages.
### Request Example
```python
data = b'0\x0e\x02\x01\x01\x16\x09Is 1+1=3?'
decoded, length = foo.decode_with_length('Question', data)
```
### Response
- **decoded** (object) - The decoded ASN.1 data structure.
- **length** (int) - The number of bytes consumed from the input buffer.
```
--------------------------------
### Handle ASN.1 ConstraintsError
Source: https://context7.com/eerimoq/asn1tools/llms.txt
Catch 'ConstraintsError' exceptions when data violates defined constraints during encoding, such as out-of-range values. Ensure 'check_constraints=True' is used for validation.
```python
import asn1tools
foo = asn1tools.compile_files('foo.asn')
try:
foo.encode('Question', {'id': -1}, check_constraints=True)
except asn1tools.ConstraintsError as e:
print(f"Constraint error: {e}")
```
--------------------------------
### Handle ASN.1 EncodeError
Source: https://context7.com/eerimoq/asn1tools/llms.txt
Catch 'EncodeError' exceptions that arise during the encoding process, for instance, when attempting to encode a type that does not exist in the specification.
```python
import asn1tools
foo = asn1tools.compile_files('foo.asn')
try:
foo.encode('NonExistentType', {})
except asn1tools.EncodeError as e:
print(f"Encode error: {e}")
```
--------------------------------
### Encode Data to Bytes
Source: https://context7.com/eerimoq/asn1tools/llms.txt
The encode method converts Python data structures into bytes based on the compiled ASN.1 schema. It supports type checking, constraint validation, and formatting for human-readable codecs.
```python
import asn1tools
foo = asn1tools.compile_files('foo.asn')
# Basic encoding
question = {'id': 1, 'question': 'Is 1+1=3?'}
encoded = foo.encode('Question', question)
print(encoded) # bytearray(b'0\x0e\x02\x01\x01\x16\x09Is 1+1=3?')
# Encode with type checking enabled (default)
encoded = foo.encode('Question', question, check_types=True)
# Encode with constraint validation
try:
encoded = foo.encode('Question', question, check_constraints=True)
except asn1tools.ConstraintsError as e:
print(f"Constraint violation: {e}")
# Encoding CHOICE types (as tuple of choice name and value)
choice_data = ('textMessage', 'Hello World')
# Assumes a CHOICE type with 'textMessage' alternative
# Encoding with indentation for human-readable formats (GSER, XER, JER)
foo_gser = asn1tools.compile_files('foo.asn', 'gser')
encoded_gser = foo_gser.encode('Question', question, indent=4)
```
--------------------------------
### Specification.decode_length
Source: https://context7.com/eerimoq/asn1tools/llms.txt
Decodes only the length header from BER/DER encoded data without parsing the full content.
```APIDOC
## Specification.decode_length
### Description
Decodes just the length from BER/DER encoded data without fully decoding the content, useful for framing and buffering.
### Response
- **length** (int|None) - The full message length, or None if insufficient data is provided.
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.