ctypes 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/.standard.yml +3 -0
- data/CODE_OF_CONDUCT.md +132 -0
- data/CONTRIBUTING.md +55 -0
- data/Gemfile +14 -0
- data/LICENSE.txt +21 -0
- data/MAINTAINERS.md +3 -0
- data/README.md +390 -0
- data/Rakefile +10 -0
- data/SECURITY.md +57 -0
- data/ctypes.gemspec +40 -0
- data/lib/ctypes/array.rb +180 -0
- data/lib/ctypes/bitfield/builder.rb +246 -0
- data/lib/ctypes/bitfield.rb +278 -0
- data/lib/ctypes/bitmap.rb +154 -0
- data/lib/ctypes/enum/builder.rb +85 -0
- data/lib/ctypes/enum.rb +201 -0
- data/lib/ctypes/exporter.rb +50 -0
- data/lib/ctypes/helpers.rb +190 -0
- data/lib/ctypes/importers/castxml/loader.rb +150 -0
- data/lib/ctypes/importers/castxml.rb +59 -0
- data/lib/ctypes/importers.rb +7 -0
- data/lib/ctypes/int.rb +147 -0
- data/lib/ctypes/missing_bytes_error.rb +24 -0
- data/lib/ctypes/pad.rb +56 -0
- data/lib/ctypes/pretty_print_helpers.rb +31 -0
- data/lib/ctypes/string.rb +154 -0
- data/lib/ctypes/struct/builder.rb +242 -0
- data/lib/ctypes/struct.rb +529 -0
- data/lib/ctypes/terminated.rb +65 -0
- data/lib/ctypes/type.rb +195 -0
- data/lib/ctypes/union/builder.rb +220 -0
- data/lib/ctypes/union.rb +637 -0
- data/lib/ctypes/version.rb +8 -0
- data/lib/ctypes.rb +102 -0
- data/sig/ctypes.rbs +4 -0
- metadata +92 -0
checksums.yaml
ADDED
@@ -0,0 +1,7 @@
|
|
1
|
+
---
|
2
|
+
SHA256:
|
3
|
+
metadata.gz: 7ec7b7f88b8d9103fce2b420944392299eb38d346757307cfa84c0f554f44799
|
4
|
+
data.tar.gz: da001e06c9e3569252953248b2dede7d1051f442329088cef30b8442ea4175ea
|
5
|
+
SHA512:
|
6
|
+
metadata.gz: 952e0fc657ccbdf8bf4b92ee0efdd2c1023aa80a9cfd4aaf3597e32c6d36cd1ea4d2eb57926868561710ee06e8c1c7810d5ba641e1eac7d8f381681ea76fdcdc
|
7
|
+
data.tar.gz: 9150e84ef5ce4e50f265b13b10b0744f384038ad6b760f98321ec7833be882b3016f8c168e348414234b72a34caad7dfc0859afa3c2cfce74501b0ca981fa882
|
data/.standard.yml
ADDED
data/CODE_OF_CONDUCT.md
ADDED
@@ -0,0 +1,132 @@
|
|
1
|
+
# Contributor Covenant Code of Conduct
|
2
|
+
|
3
|
+
## Our Pledge
|
4
|
+
|
5
|
+
We as members, contributors, and leaders pledge to make participation in our
|
6
|
+
community a harassment-free experience for everyone, regardless of age, body
|
7
|
+
size, visible or invisible disability, ethnicity, sex characteristics, gender
|
8
|
+
identity and expression, level of experience, education, socio-economic status,
|
9
|
+
nationality, personal appearance, race, caste, color, religion, or sexual
|
10
|
+
identity and orientation.
|
11
|
+
|
12
|
+
We pledge to act and interact in ways that contribute to an open, welcoming,
|
13
|
+
diverse, inclusive, and healthy community.
|
14
|
+
|
15
|
+
## Our Standards
|
16
|
+
|
17
|
+
Examples of behavior that contributes to a positive environment for our
|
18
|
+
community include:
|
19
|
+
|
20
|
+
* Demonstrating empathy and kindness toward other people
|
21
|
+
* Being respectful of differing opinions, viewpoints, and experiences
|
22
|
+
* Giving and gracefully accepting constructive feedback
|
23
|
+
* Accepting responsibility and apologizing to those affected by our mistakes,
|
24
|
+
and learning from the experience
|
25
|
+
* Focusing on what is best not just for us as individuals, but for the overall
|
26
|
+
community
|
27
|
+
|
28
|
+
Examples of unacceptable behavior include:
|
29
|
+
|
30
|
+
* The use of sexualized language or imagery, and sexual attention or advances of
|
31
|
+
any kind
|
32
|
+
* Trolling, insulting or derogatory comments, and personal or political attacks
|
33
|
+
* Public or private harassment
|
34
|
+
* Publishing others' private information, such as a physical or email address,
|
35
|
+
without their explicit permission
|
36
|
+
* Other conduct which could reasonably be considered inappropriate in a
|
37
|
+
professional setting
|
38
|
+
|
39
|
+
## Enforcement Responsibilities
|
40
|
+
|
41
|
+
Community leaders are responsible for clarifying and enforcing our standards of
|
42
|
+
acceptable behavior and will take appropriate and fair corrective action in
|
43
|
+
response to any behavior that they deem inappropriate, threatening, offensive,
|
44
|
+
or harmful.
|
45
|
+
|
46
|
+
Community leaders have the right and responsibility to remove, edit, or reject
|
47
|
+
comments, commits, code, wiki edits, issues, and other contributions that are
|
48
|
+
not aligned to this Code of Conduct, and will communicate reasons for moderation
|
49
|
+
decisions when appropriate.
|
50
|
+
|
51
|
+
## Scope
|
52
|
+
|
53
|
+
This Code of Conduct applies within all community spaces, and also applies when
|
54
|
+
an individual is officially representing the community in public spaces.
|
55
|
+
Examples of representing our community include using an official email address,
|
56
|
+
posting via an official social media account, or acting as an appointed
|
57
|
+
representative at an online or offline event.
|
58
|
+
|
59
|
+
## Enforcement
|
60
|
+
|
61
|
+
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
62
|
+
reported to the community leaders responsible for enforcement at
|
63
|
+
`dlary[at]cisco<dot>com`. All complaints will be reviewed and investigated
|
64
|
+
promptly and fairly.
|
65
|
+
|
66
|
+
All community leaders are obligated to respect the privacy and security of the
|
67
|
+
reporter of any incident.
|
68
|
+
|
69
|
+
## Enforcement Guidelines
|
70
|
+
|
71
|
+
Community leaders will follow these Community Impact Guidelines in determining
|
72
|
+
the consequences for any action they deem in violation of this Code of Conduct:
|
73
|
+
|
74
|
+
### 1. Correction
|
75
|
+
|
76
|
+
**Community Impact**: Use of inappropriate language or other behavior deemed
|
77
|
+
unprofessional or unwelcome in the community.
|
78
|
+
|
79
|
+
**Consequence**: A private, written warning from community leaders, providing
|
80
|
+
clarity around the nature of the violation and an explanation of why the
|
81
|
+
behavior was inappropriate. A public apology may be requested.
|
82
|
+
|
83
|
+
### 2. Warning
|
84
|
+
|
85
|
+
**Community Impact**: A violation through a single incident or series of
|
86
|
+
actions.
|
87
|
+
|
88
|
+
**Consequence**: A warning with consequences for continued behavior. No
|
89
|
+
interaction with the people involved, including unsolicited interaction with
|
90
|
+
those enforcing the Code of Conduct, for a specified period of time. This
|
91
|
+
includes avoiding interactions in community spaces as well as external channels
|
92
|
+
like social media. Violating these terms may lead to a temporary or permanent
|
93
|
+
ban.
|
94
|
+
|
95
|
+
### 3. Temporary Ban
|
96
|
+
|
97
|
+
**Community Impact**: A serious violation of community standards, including
|
98
|
+
sustained inappropriate behavior.
|
99
|
+
|
100
|
+
**Consequence**: A temporary ban from any sort of interaction or public
|
101
|
+
communication with the community for a specified period of time. No public or
|
102
|
+
private interaction with the people involved, including unsolicited interaction
|
103
|
+
with those enforcing the Code of Conduct, is allowed during this period.
|
104
|
+
Violating these terms may lead to a permanent ban.
|
105
|
+
|
106
|
+
### 4. Permanent Ban
|
107
|
+
|
108
|
+
**Community Impact**: Demonstrating a pattern of violation of community
|
109
|
+
standards, including sustained inappropriate behavior, harassment of an
|
110
|
+
individual, or aggression toward or disparagement of classes of individuals.
|
111
|
+
|
112
|
+
**Consequence**: A permanent ban from any sort of public interaction within the
|
113
|
+
community.
|
114
|
+
|
115
|
+
## Attribution
|
116
|
+
|
117
|
+
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
118
|
+
version 2.1, available at
|
119
|
+
[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
|
120
|
+
|
121
|
+
Community Impact Guidelines were inspired by [Mozilla's code of conduct
|
122
|
+
enforcement ladder][Mozilla CoC].
|
123
|
+
|
124
|
+
For answers to common questions about this code of conduct, see the FAQ at
|
125
|
+
[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
|
126
|
+
[https://www.contributor-covenant.org/translations][translations].
|
127
|
+
|
128
|
+
[homepage]: https://www.contributor-covenant.org
|
129
|
+
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
|
130
|
+
[Mozilla CoC]: https://github.com/mozilla/diversity
|
131
|
+
[FAQ]: https://www.contributor-covenant.org/faq
|
132
|
+
[translations]: https://www.contributor-covenant.org/translations
|
data/CONTRIBUTING.md
ADDED
@@ -0,0 +1,55 @@
|
|
1
|
+
# How to Contribute
|
2
|
+
|
3
|
+
Thanks for your interest in contributing to `ctypes`! Here are a few
|
4
|
+
general guidelines on contributing and reporting bugs that we ask you to review.
|
5
|
+
Following these guidelines helps to communicate that you respect the time of the
|
6
|
+
contributors managing and developing this open source project. In return, they
|
7
|
+
should reciprocate that respect in addressing your issue, assessing changes, and
|
8
|
+
helping you finalize your pull requests. In that spirit of mutual respect, we
|
9
|
+
endeavor to review incoming issues and pull requests within 10 days, and will
|
10
|
+
close any lingering issues or pull requests after 60 days of inactivity.
|
11
|
+
|
12
|
+
Please note that all of your interactions in the project are subject to our
|
13
|
+
[Code of Conduct](/CODE_OF_CONDUCT.md). This includes creation of issues or pull
|
14
|
+
requests, commenting on issues or pull requests, and extends to all interactions
|
15
|
+
in any real-time space e.g., Slack, Discord, etc.
|
16
|
+
|
17
|
+
## Reporting Issues
|
18
|
+
|
19
|
+
Before reporting a new issue, please ensure that the issue was not already
|
20
|
+
reported or fixed by searching through our
|
21
|
+
[issues list](https://github.com/cisco-open/ctypes/issues).
|
22
|
+
|
23
|
+
When creating a new issue, please be sure to include a **title and clear
|
24
|
+
description**, as much relevant information as possible, and, if possible, a
|
25
|
+
test case.
|
26
|
+
|
27
|
+
**If you discover a security bug, please do not report it through GitHub.
|
28
|
+
Instead, please see security procedures in [SECURITY.md](/SECURITY.md).**
|
29
|
+
|
30
|
+
## Sending Pull Requests
|
31
|
+
|
32
|
+
Before sending a new pull request, take a look at existing pull requests and
|
33
|
+
issues to see if the proposed change or fix has been discussed in the past, or
|
34
|
+
if the change was already implemented but not yet released.
|
35
|
+
|
36
|
+
We expect new pull requests to include tests for any affected behavior, and,
|
37
|
+
as we follow semantic versioning, we may reserve breaking changes until the
|
38
|
+
next major version release.
|
39
|
+
|
40
|
+
## Other Ways to Contribute
|
41
|
+
|
42
|
+
We welcome anyone that wants to contribute to `ctypes` to triage and
|
43
|
+
reply to open issues to help troubleshoot and fix existing bugs. Here is what
|
44
|
+
you can do:
|
45
|
+
|
46
|
+
- Help ensure that existing issues follows the recommendations from the
|
47
|
+
_[Reporting Issues](#reporting-issues)_ section, providing feedback to the
|
48
|
+
issue's author on what might be missing.
|
49
|
+
- Review existing pull requests, and testing patches against real existing
|
50
|
+
applications that use `ctypes`.
|
51
|
+
- Write a test, or add a missing test case to an existing test.
|
52
|
+
|
53
|
+
Thanks again for your interest on contributing to `ctypes`!
|
54
|
+
|
55
|
+
:heart:
|
data/Gemfile
ADDED
@@ -0,0 +1,14 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
source "https://rubygems.org"
|
4
|
+
|
5
|
+
# Specify your gem's dependencies in ctypes.gemspec
|
6
|
+
gemspec
|
7
|
+
|
8
|
+
gem "nokogiri", "~> 1.13", require: false
|
9
|
+
gem "pry", "~> 0.14"
|
10
|
+
gem "pry-rescue", "~> 1.5"
|
11
|
+
gem "pry-stack_explorer", "~> 0.6"
|
12
|
+
gem "rake", "~> 13.0"
|
13
|
+
gem "rspec", "~> 3.0"
|
14
|
+
gem "standard", "~> 1.3"
|
data/LICENSE.txt
ADDED
@@ -0,0 +1,21 @@
|
|
1
|
+
The MIT License (MIT)
|
2
|
+
|
3
|
+
Copyright (c) 2024 Cisco
|
4
|
+
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
7
|
+
in the Software without restriction, including without limitation the rights
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
10
|
+
furnished to do so, subject to the following conditions:
|
11
|
+
|
12
|
+
The above copyright notice and this permission notice shall be included in
|
13
|
+
all copies or substantial portions of the Software.
|
14
|
+
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
21
|
+
THE SOFTWARE.
|
data/MAINTAINERS.md
ADDED
data/README.md
ADDED
@@ -0,0 +1,390 @@
|
|
1
|
+
# CTypes Ruby Gem
|
2
|
+
|
3
|
+
[](https://rubygems.org/gems/ctypes)
|
4
|
+
[](http://github.com/cisco-open/ruby-ctypes)
|
5
|
+
[](http://rubydoc.org/gems/ruby-ctypes/frames)
|
6
|
+
|
7
|
+
[](CODE_OF_CONDUCT.md)
|
8
|
+
[](https://opensource.cisco.com)
|
9
|
+
|
10
|
+
Manipulate common C types in Ruby.
|
11
|
+
|
12
|
+
- unpack complex binary data into ruby types, modify, and repack them as binary
|
13
|
+
- bounds checking on types (when packing)
|
14
|
+
- complex types supported
|
15
|
+
- structs with flexible array members
|
16
|
+
- arrays terminated by specific values
|
17
|
+
- strings terminated by a specific byte sequence
|
18
|
+
- flexible endian support
|
19
|
+
- default endian globally configurable; defaults to host endian
|
20
|
+
- individual types can have fixed-endian
|
21
|
+
- structs support per attribute endian
|
22
|
+
- minimal reserved words for Union and Struct types
|
23
|
+
- want to avoid colliding with struct & union field names so you don't have
|
24
|
+
to rename fields like `len`
|
25
|
+
- reloadable type definitions (pry `reload-code` friendly)
|
26
|
+
- useful for using REPL-based development
|
27
|
+
|
28
|
+
## Comparisons
|
29
|
+
- BinData gem:
|
30
|
+
- Tightly coupled with file I/O
|
31
|
+
- no support for non-blocking I/O (non-blocking network sockets)
|
32
|
+
- reserves common struct attribute names such as `len`
|
33
|
+
- does not support reloading of types (pry `reload-code`)
|
34
|
+
- Fiddle gem:
|
35
|
+
- only supports native endian
|
36
|
+
- no support for dynamically sized & terminated types
|
37
|
+
|
38
|
+
## Installation
|
39
|
+
|
40
|
+
Install the gem and add to the application's Gemfile by executing:
|
41
|
+
|
42
|
+
$ bundle add ctypes
|
43
|
+
|
44
|
+
If bundler is not being used to manage dependencies, install the gem by executing:
|
45
|
+
|
46
|
+
$ gem install ctypes
|
47
|
+
|
48
|
+
## Usage
|
49
|
+
|
50
|
+
### Basic types
|
51
|
+
```ruby
|
52
|
+
require "ctypes"
|
53
|
+
|
54
|
+
# load optional helpers for common types
|
55
|
+
include CTypes::Helpers
|
56
|
+
|
57
|
+
# common integer types all defined: uint64, int64, ..., uint8, int8
|
58
|
+
# can be used to pack and unpack values
|
59
|
+
uint32.pack(0xfeedface) # => "\xce\xfa\xed\xfe"
|
60
|
+
uint32.pack(0xfeedface, endian: :big) # => "\xfe\xed\xfa\xce"
|
61
|
+
uint32.unpack("\xce\xfa\xed\xfe") # => 0xfeedface
|
62
|
+
uint32.unpack("\xfe\xed\xfa\xce", endian: :big)
|
63
|
+
# => 0xfeedface
|
64
|
+
|
65
|
+
# `unpack_one` can be used to manually unpack sequential types from a string. # We recommend using `CTypes::Struct` for complex types, but this approach
|
66
|
+
# can be useful when exploring binary data.
|
67
|
+
buf = "\xaa\xbb\xcc\xdd\x11\x22"
|
68
|
+
word, buf = uint32.unpack_one(buf) # => [0xddccbbaa, "\x11\x22"]
|
69
|
+
hword, buf = uint16.unpack_one(buf) # => [0x2211, ""]
|
70
|
+
|
71
|
+
# create fixed-endian types from existing types
|
72
|
+
u32be = uint32.with_endian(:big)
|
73
|
+
u32be.pack(0xfeedface) # => "\xfe\xed\xfa\xce"
|
74
|
+
|
75
|
+
# c strings (char[], uint8[], int8[]) supported by string
|
76
|
+
string.unpack("hello world\0\0\0\0") # => "hello world"
|
77
|
+
string.pack("hello world") # => "hello world"
|
78
|
+
|
79
|
+
# note: by default strings are greedy; they will consume all bytes in the
|
80
|
+
# input, but only return the bytes up to the first null byte
|
81
|
+
string.unpack("first\0second\0") # => ["first", ""]
|
82
|
+
|
83
|
+
# to unpack null-terminated strings use string.terminated
|
84
|
+
_, rest = string.terminated.unpack("first\0second\0")
|
85
|
+
# => ["first", "second\x00"]
|
86
|
+
string.terminated.unpack(rest) # => ["second", ""]
|
87
|
+
string.terminated.pack("first") # => "first\0"
|
88
|
+
|
89
|
+
# other bytes can be used to terminate strings
|
90
|
+
t = string.terminated("\xff")
|
91
|
+
t.unpack("test\xff") # => "test"
|
92
|
+
t.pack("hello\0world") # => "hello\x00world\xFF"
|
93
|
+
|
94
|
+
# along with byte sequences
|
95
|
+
t = string.terminated("STOP")
|
96
|
+
t.unpack("this is the messageSTOPnext messageSTOP")
|
97
|
+
# => "this is the message"
|
98
|
+
t.pack("this is a reply") # => "this is a replySTOP"
|
99
|
+
|
100
|
+
# fixed-width string (char[16])
|
101
|
+
string(16).pack("hello world") # => "hello world\0\0\0\0\0"
|
102
|
+
string(16).unpack("hello world\0\0\0\0\0") # => "hello world\0\0\0\0\0"
|
103
|
+
string(16).unpack("hello world") # => Exception raised
|
104
|
+
|
105
|
+
# fixed-width string, but preserve null bytes when unpacking
|
106
|
+
char_16 = string(16, trim: false)
|
107
|
+
char_16.unpack("hello world\0\0\0\0\0") # => "hello world\0\0\0\0\0"
|
108
|
+
char_16.pack("hello world") # => "hello world\0\0\0\0\0"
|
109
|
+
|
110
|
+
```
|
111
|
+
|
112
|
+
### Arrays
|
113
|
+
```ruby
|
114
|
+
require "ctypes"
|
115
|
+
include CTypes::Helpers
|
116
|
+
|
117
|
+
# fixed-length arrays
|
118
|
+
pair = array(uint32, 2)
|
119
|
+
pair.unpack("\x01\x02\x03\x04\x05\x06\x07\x08")
|
120
|
+
# => [0x04030201, 0x08070605]
|
121
|
+
pair.unpack("\x01\x02\x03\x04\x05\x06\x07\x08\xff\xff\xff\xff")
|
122
|
+
# => [0x04030201, 0x08070605]
|
123
|
+
|
124
|
+
# dynamic length (greedy) arrays
|
125
|
+
bytes = array(uint8)
|
126
|
+
bytes.unpack("hello") # => [104, 101, 108, 108, 111]
|
127
|
+
bytes.unpack("\1\2\3") # => [1, 2, 3]
|
128
|
+
bytes.pack([4,5,6]) # => "\4\5\6"
|
129
|
+
|
130
|
+
# any type can be converted to a fixed-endian type
|
131
|
+
be_pair = pair.with_endian(:big)
|
132
|
+
be_pair.unpack("\x01\x02\x03\x04\x05\x06\x07\x08")
|
133
|
+
# => [0x01020304, 0x05060708]
|
134
|
+
|
135
|
+
# and it can be done for the inner type too
|
136
|
+
be_pair_inner = array(uint8.with_endian(:big))
|
137
|
+
be_pair_inner.unpack("\x01\x02\x03\x04\x05\x06\x07\x08")
|
138
|
+
# => [0x01020304, 0x05060708]
|
139
|
+
|
140
|
+
# array of null-terminated strings, terminated by an empty string
|
141
|
+
strings = array(string.terminated("\0"), terminator: "")
|
142
|
+
strings.unpack("first\0second\0third\0\0")
|
143
|
+
# => ["first", "second", "third"]
|
144
|
+
|
145
|
+
# array of integers, terminated by -1
|
146
|
+
ints = array(int8, terminator: -1)
|
147
|
+
ints.pack([1, 2, 3, 4]) # => "\x01\x02\x03\x04\xFF"
|
148
|
+
ints.unpack("\x01\x02\x03\x04\xFFtail") # => [1, 2, 3, 4]
|
149
|
+
ints.unpack_one("\x01\x02\x03\x04\xFFtail") # => [[1, 2, 3, 4], "tail"]
|
150
|
+
|
151
|
+
# array of structs; terminated by the :end type
|
152
|
+
type = struct do
|
153
|
+
attribute :type, enum(uint8, %i[record end])
|
154
|
+
attribute :value, uint32
|
155
|
+
end
|
156
|
+
records = array(type, terminator: {type: :end, value: 0})
|
157
|
+
records.pack([{type: :record, value: 0xffff}])
|
158
|
+
# => "\x00\xFF\xFF\x00\x00\x01\x00\x00\x00\x00"
|
159
|
+
records.unpack("\x00\xFF\xFF\x00\x00\x01\x00\x00\x00\x00")
|
160
|
+
# => struct {
|
161
|
+
# .type = :record,
|
162
|
+
# .value = 65535 (0xffff), }
|
163
|
+
```
|
164
|
+
|
165
|
+
### Enums
|
166
|
+
```ruby
|
167
|
+
require "ctypes"
|
168
|
+
include CTypes::Helpers
|
169
|
+
|
170
|
+
# default enum is uint32, start numbering at zero
|
171
|
+
state = enum(%i[invalid running sleep blocked])
|
172
|
+
state.pack(:running) # => "\1\0\0\0"
|
173
|
+
|
174
|
+
# can use other integer types
|
175
|
+
state = enum(uint8, %i[invalid running sleep blocked])
|
176
|
+
state.pack(:running) # => "\1"
|
177
|
+
|
178
|
+
# can be sparse
|
179
|
+
state = enum(uint8, {invalid: 0, running: 5, sleep: 6, blocked: 0xff})
|
180
|
+
state.pack(:blocked) # => "\xff"
|
181
|
+
|
182
|
+
# same as above with block syntax
|
183
|
+
state = enum(uint8) do |e|
|
184
|
+
e << :invalid
|
185
|
+
e << {running: 5}
|
186
|
+
e << :sleep # assigned value 6
|
187
|
+
e << {blocked: 0xff}
|
188
|
+
end
|
189
|
+
state.pack(:blocked) # => "\xff"
|
190
|
+
```
|
191
|
+
|
192
|
+
### Structures
|
193
|
+
```ruby
|
194
|
+
# Declare a TLV struct. Size of each structure is determined by the `len`
|
195
|
+
# field.
|
196
|
+
class TLV < CTypes::Struct
|
197
|
+
layout do
|
198
|
+
endian :big # all fields will use network-byte order
|
199
|
+
attribute :type, enum(uint8, %i[invalid hello read write goodbye])
|
200
|
+
attribute :len, uint32
|
201
|
+
attribute :value, string
|
202
|
+
# dynamically determine the size of the struct when unpacking
|
203
|
+
size { |struct| offsetof(:value) + struct[:len] }
|
204
|
+
end
|
205
|
+
end
|
206
|
+
|
207
|
+
# pack the tlv struct
|
208
|
+
version = "v1.0"
|
209
|
+
TLV.pack({type: :hello, len: version.size, value: version})
|
210
|
+
# => "\x01\x04\x00\x00\x00v1.0"
|
211
|
+
|
212
|
+
# unpack a binary structure
|
213
|
+
msg = TLV.unpack("\x01\x04\x00\x00\x00v1.0")
|
214
|
+
msg.type # => :hello
|
215
|
+
msg.value # => "v1.0"
|
216
|
+
|
217
|
+
# modify the structure and repack into binary representation
|
218
|
+
msg.type = :goodbye
|
219
|
+
msg.len = 0
|
220
|
+
msg.to_binstr # => "\x04\x00\x00\x00\x00"
|
221
|
+
```
|
222
|
+
|
223
|
+
### Unions
|
224
|
+
Note: because the underlying memory for union values is not shared between each
|
225
|
+
member, accessing multiple members in a union does have a performance penalty
|
226
|
+
to pack the existing member and unpack the new member. This penalty can be
|
227
|
+
avoided for read-only unions by freezing the union instance.
|
228
|
+
|
229
|
+
```ruby
|
230
|
+
class Msg < CTypes::Union
|
231
|
+
layout do
|
232
|
+
endian :big # network byte-order
|
233
|
+
|
234
|
+
type = enum(uint8, {invalid: 0, hello: 1, read: 2})
|
235
|
+
member :hello, struct({type:, version: string})
|
236
|
+
member :read, struct({type:, offset: uint64, len: uint64})
|
237
|
+
member :type, type
|
238
|
+
end
|
239
|
+
end
|
240
|
+
|
241
|
+
# provide only one member when packing
|
242
|
+
Msg.pack({hello: {type: :hello, version: "v1.0"}}) # => "\x01v1.0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
|
243
|
+
Msg.pack({read: {type: :read, offset: 0xfeed, len: 0xdddd}}) # => "\x02\x00\x00\x00\x00\x00\x00\xFE\xED\x00\x00\x00\x00\x00\x00\xDD\xDD"
|
244
|
+
|
245
|
+
# unpack a message and access member values
|
246
|
+
msg = Msg.unpack("\x02" +
|
247
|
+
"\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe" +
|
248
|
+
"\xab\xab\xab\xab\xab\xab\xab\xab")
|
249
|
+
msg.type # => :read
|
250
|
+
msg.read.offset # => 18374403900871474942
|
251
|
+
msg.read.len # => 12370169555311111083
|
252
|
+
|
253
|
+
# modify and pack into binary
|
254
|
+
msg.hello.type = :hello
|
255
|
+
msg.hello.version = "v1.0"
|
256
|
+
msg.to_binstr # => "\x01v1.0\xFE\xFE\xFE\xFE\xAB\xAB\xAB\xAB\xAB\xAB\xAB\xAB"
|
257
|
+
```
|
258
|
+
|
259
|
+
### Terminated
|
260
|
+
Some greedy dynamic length types are terminated with byte sequences, or
|
261
|
+
variable byte sequences. To handle these types we use CTypes::Terminated.
|
262
|
+
|
263
|
+
```ruby
|
264
|
+
# string.terminated returns a CTypes::Terminated instance
|
265
|
+
telegram = string.terminated("STOP")
|
266
|
+
telegrams = array(telegram)
|
267
|
+
telegrams.unpack("hello worldSTOPnext messageSTOP")
|
268
|
+
# => ["hello world", "next message"]
|
269
|
+
|
270
|
+
|
271
|
+
# record is an id along with an array of data bytes
|
272
|
+
record = struct({id: uint8, data: array(uint8)})
|
273
|
+
# each record is terminated with the byte sequence \xff\xee (for reasons?)
|
274
|
+
term = "\xff\xee"
|
275
|
+
# create a terminated type for the record (yea, it is ugly right now)
|
276
|
+
terminated_record = CTypes::Terminated
|
277
|
+
.new(type: record,
|
278
|
+
locate: proc { |b,_| [b.index(term), term.size] },
|
279
|
+
terminate: term)
|
280
|
+
# and then an array of terminated records type
|
281
|
+
records = array(terminated_record)
|
282
|
+
|
283
|
+
# now pack & unpack as needed
|
284
|
+
records.pack([
|
285
|
+
{id: 1, data: [1, 2, 3, 4]},
|
286
|
+
{id: 2, data: [5, 5]},
|
287
|
+
{id: 3}
|
288
|
+
]) # => "\x01\x01\x02\x03\x04\xFF\xEE\x02\x05\x05\xFF\xEE\x03\xFF\xEE"
|
289
|
+
records.unpack("\x01\x01\x02\x03\x04\xFF\xEE\x02\x05\x05\xFF\xEE\x03\xFF\xEE")
|
290
|
+
# => [#<struct id=1, data=[1, 2, 3, 4]>,
|
291
|
+
# #<struct id=2, data=[5, 5]>,
|
292
|
+
# #<struct id=3, data=[]>]
|
293
|
+
```
|
294
|
+
|
295
|
+
### Custom Types
|
296
|
+
Custom types can be created then used within other CTypes. The following is an
|
297
|
+
custom CTypes implementation of the DWARF ULEB128 datatype. It is a compressed
|
298
|
+
representation of a 128-bit integer that uses 7 bits per byte for the encoded
|
299
|
+
value, with the highest bit set on the last byte of the value. The bytes are
|
300
|
+
stored in little endian order.
|
301
|
+
|
302
|
+
```ruby
|
303
|
+
module ULEB128
|
304
|
+
extend CTypes::Type
|
305
|
+
|
306
|
+
# declare the underlying DRY type; it must have a default value, and may
|
307
|
+
# have constraints set
|
308
|
+
@dry_type = Dry::Types["integer"].default(0)
|
309
|
+
|
310
|
+
# as this is a dynamically sized type, let's set size to be the minimum size
|
311
|
+
# for the type (1 byte), and ensure .fixed_size? returns false
|
312
|
+
@size = 1
|
313
|
+
def self.fixed_size?
|
314
|
+
false
|
315
|
+
end
|
316
|
+
|
317
|
+
# provide a method for packing the ruby value into the binary representation
|
318
|
+
def self.pack(value, endian: default_endian, validate: true)
|
319
|
+
return "\x80" if value == 0
|
320
|
+
buf = String.new
|
321
|
+
while value != 0
|
322
|
+
buf << (value & 0x7f)
|
323
|
+
value >>= 7
|
324
|
+
end
|
325
|
+
buf[-1] = (buf[-1].ord | 0x80).chr
|
326
|
+
buf
|
327
|
+
end
|
328
|
+
|
329
|
+
# provide a method for unpacking an instance of this type from a String, and
|
330
|
+
# returning both the unpacked value, and any unused input
|
331
|
+
def self.unpack_one(buf, endian: default_endian)
|
332
|
+
value = 0
|
333
|
+
shift = 0
|
334
|
+
len = 0
|
335
|
+
buf.each_byte do |b|
|
336
|
+
len += 1
|
337
|
+
value |= ((b & 0x7f) << shift)
|
338
|
+
return value, buf[len...] if (b & 0x80) != 0
|
339
|
+
shift += 7
|
340
|
+
end
|
341
|
+
raise TerminatorNotFoundError
|
342
|
+
end
|
343
|
+
end
|
344
|
+
|
345
|
+
# now the type can be used like any other type
|
346
|
+
ULEB128.unpack_one("\x7f\x7f\x83XXX") # => [0xffff, "XXX"]
|
347
|
+
ULEB128.unpack("\x7f\x7f\x83") # => 0xffff
|
348
|
+
ULEB128.unpack("\x81XXX") # => 1
|
349
|
+
ULEB128.pack(0) # => "\x80"
|
350
|
+
ULEB128.pack(1) # => "\x81"
|
351
|
+
ULEB128.pack(0xffff) # => "\x7F\x7F\x83"
|
352
|
+
|
353
|
+
# use it in an array
|
354
|
+
list = array(ULEB128)
|
355
|
+
list.unpack("\x7f\x7f\x83\x81\x80") # => [65535, 1, 0]
|
356
|
+
|
357
|
+
# or a struct
|
358
|
+
t = struct(id: uint32, value: ULEB128)
|
359
|
+
t.unpack("\1\0\0\0\x7f\x7f\x83XXX") # => #<struct id=1, value=65535>
|
360
|
+
```
|
361
|
+
|
362
|
+
## Roadmap
|
363
|
+
|
364
|
+
See the [open issues](https://github.com/cisco-open/ruby-ctypes/issues) for a
|
365
|
+
list of proposed features (and known issues).
|
366
|
+
|
367
|
+
## Development
|
368
|
+
|
369
|
+
After checking out the repo, run `bundle install` to install dependencies.
|
370
|
+
Then, run `rake spec` to run the tests. You can also run `bin/console` for an
|
371
|
+
interactive prompt that will allow you to experiment.
|
372
|
+
|
373
|
+
To install this gem onto your local machine, run `bundle exec rake install`. To
|
374
|
+
release a new version, update the version number in `version.rb`, and then run
|
375
|
+
`bundle exec rake release`, which will create a git tag for the version, push
|
376
|
+
git commits and the created tag, and push the `.gem` file to
|
377
|
+
[rubygems.org](https://rubygems.org).
|
378
|
+
|
379
|
+
## Contributing
|
380
|
+
|
381
|
+
Contributions are what make the open source community such an amazing place to
|
382
|
+
learn, inspire, and create. Any contributions you make are **greatly
|
383
|
+
appreciated**. For detailed contributing guidelines, please see
|
384
|
+
[CONTRIBUTING.md](CONTRIBUTING.md)
|
385
|
+
|
386
|
+
## License
|
387
|
+
|
388
|
+
The gem is available as open source under the terms of the
|
389
|
+
[MIT License](https://opensource.org/licenses/MIT).
|
390
|
+
License. See [LICENSE.txt](LICENSE.txt) for more information.
|