Skip to content

Commit 3ff569a

Browse files
committed
Change option to buffer_support & improve readme
1 parent 4b0cd7c commit 3ff569a

File tree

7 files changed

+37
-33
lines changed

7 files changed

+37
-33
lines changed

Diff for: README.md

+13-9
Original file line numberDiff line numberDiff line change
@@ -6,22 +6,26 @@ and enums
66
## Goals
77

88
- Generate TypeScript code directly from Rust source
9-
- Work from `build.rs`
9+
- TypeScript must compile with [`strict` mode enabled](https://github.com/timfish/bincode-typescript/blob/master/tests/build.rs)
1010
- Avoid Object Orientated TypeScript for better tree-shaking and optimisation
11-
- TypeScript for enums/structs should be ergonomic and high performance
11+
- TypeScript should be ergonomic and high performance
1212
- Use `const enum` for Unit enums and respect discriminant values!
13-
- Use `TypedArray`s for `Vec<{integer,float}>` for greater performance
13+
- Use `TypedArray` and copy byte blocks for `Vec<{integer,float}>` for greater performance
1414

1515
## Status
1616

1717
I'm pretty new to Rust and I've just hacked around until the tests pass 🤷‍♂️
1818

1919
There is much room for improvement and PRs are welcome!
2020

21-
Check out the [Rust
22-
code](https://github.com/timfish/bincode-typescript/blob/master/tests/test_types.rs)
23-
used in the tests and the [generated
24-
TypeScript](https://github.com/timfish/bincode-typescript/blob/master/tests/test_types.ts) code.
21+
Check the source for [currently supported Rust types and their TypeScript
22+
equivalents](https://github.com/timfish/bincode-typescript/blob/master/src/types.rs#L30).
23+
24+
You may also like to look at the [Rust
25+
types](https://github.com/timfish/bincode-typescript/blob/master/tests/test_types.rs)
26+
used in the tests and the [TypeScript
27+
generated](https://github.com/timfish/bincode-typescript/blob/master/tests/test_types.ts)
28+
from these.
2529

2630
## Current Issues & Limitations
2731

@@ -30,7 +34,7 @@ TypeScript](https://github.com/timfish/bincode-typescript/blob/master/tests/test
3034
- All types must be in a single file
3135
- Serde attributes are not currently respected
3236
- `Vec<T>` are always converted to `Uint8Array/Int8Array/etc` whenever possible
33-
and this might not be particularly ergonomic from TypeScript.
37+
and this might not always be desired.
3438
- Generated code will not work on node < v11 due to the global usage of `TextEncoder/TextDecoder`
3539

3640
## Example via `build.rs`
@@ -44,7 +48,7 @@ bincode_typescript::from_file("./src/types.rs", "./ts/types.ts", false);
4448

4549
## Example via CLI
4650

47-
There is currently a single option (`--support-buffer`) to enable support for node.js
51+
There is currently a single option (`--buffer-support`) to enable support for node.js
4852
`Buffer`.
4953

5054
```shell

Diff for: src/bin.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,11 @@ use std::{
66

77
fn main() -> Result<(), Box<dyn Error>> {
88
let args: Vec<String> = std::env::args().collect();
9-
let support_buffer = args.contains(&"--support-buffer".to_string());
9+
let buffer_support = args.contains(&"--buffer-support".to_string());
1010
let input = args.last().expect("Could not find input file name");
1111

1212
let rust = fs::read_to_string(input)?;
13-
println!("{}", from_string(&rust, support_buffer)?);
13+
println!("{}", from_string(&rust, buffer_support)?);
1414

1515
Ok(())
1616
}

Diff for: src/lib.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -52,9 +52,9 @@ impl<'ast> Visit<'ast> for CodeVisitor {
5252
}
5353
}
5454

55-
pub fn from_string(input: &str, support_buffer: bool) -> Result<String, Box<dyn Error>> {
55+
pub fn from_string(input: &str, buffer_support: bool) -> Result<String, Box<dyn Error>> {
5656
let ast = syn::parse_file(input)?;
57-
let mut enum_visit = CodeVisitor::new(support_buffer);
57+
let mut enum_visit = CodeVisitor::new(buffer_support);
5858
enum_visit.visit_file(&ast);
5959

6060
Ok(enum_visit.render()?)
@@ -63,11 +63,11 @@ pub fn from_string(input: &str, support_buffer: bool) -> Result<String, Box<dyn
6363
pub fn from_file<P1: AsRef<Path>, P2: AsRef<Path>>(
6464
input: P1,
6565
output: P2,
66-
support_buffer: bool,
66+
buffer_support: bool,
6767
) -> Result<(), Box<dyn Error>> {
6868
fs::create_dir_all(&output.as_ref().parent().unwrap())?;
6969
let rust = fs::read_to_string(input)?;
70-
let typescript = from_string(&rust, support_buffer)?;
70+
let typescript = from_string(&rust, buffer_support)?;
7171
fs::write(output, typescript)?;
7272

7373
Ok(())

Diff for: src/types.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -93,8 +93,8 @@ impl RustType {
9393
RustType::Vec(t) => format!("writeSeq({})", t.writer()),
9494
RustType::TypedArray(_) => "writeTypedArray".to_string(),
9595
RustType::Tuple(t) => format!(
96-
"writeTuple<[{}]>({})",
97-
t.iter().map(|t| t.ts_type()).collect::<Vec<_>>().join(", "),
96+
"writeTuple<{}>({})",
97+
self.ts_type(),
9898
t.iter().map(|t| t.writer()).collect::<Vec<_>>().join(", ")
9999
),
100100
RustType::HashMap(k, v) => format!("writeMap({}, {})", k.writer(), v.writer()),
@@ -122,10 +122,10 @@ impl RustType {
122122
RustType::String => "readString".to_string(),
123123
RustType::Option(t) => format!("readOption({})", t.reader()),
124124
RustType::Vec(t) => format!("readSeq({})", t.reader()),
125-
RustType::TypedArray(_) => format!("readTypedArray({0})", self.ts_type()),
125+
RustType::TypedArray(_) => format!("readTypedArray({})", self.ts_type()),
126126
RustType::Tuple(t) => format!(
127-
"readTuple<[{}]>({})",
128-
t.iter().map(|t| t.ts_type()).collect::<Vec<_>>().join(", "),
127+
"readTuple<{}>({})",
128+
self.ts_type(),
129129
t.iter().map(|t| t.reader()).collect::<Vec<_>>().join(", ")
130130
),
131131
RustType::HashMap(k, v) => format!("readMap({}, {})", k.reader(), v.reader()),

Diff for: templates/enum_complex.ts.j2

+2-2
Original file line numberDiff line numberDiff line change
@@ -108,13 +108,13 @@ export function read{{ident}}(sinkOrBuf: SinkOrBuf): {{ident}} {
108108
{%- for ty in types %}
109109
{{ ty.reader() }}(sink),
110110
{%- endfor %}
111-
);
111+
);
112112
{%- when EnumVariantDeclaration::Named with { ident, types } %}
113113
return {{type_variant}}.{{ident}}({
114114
{%- for (id, ty) in types %}
115115
{{ id }}: {{ ty.reader() }}(sink),
116116
{%- endfor %}
117-
});
117+
});
118118
{%- endmatch -%}
119119
{%- endfor %}
120120
default:

Diff for: tests/test_types.ts

+8-8
Original file line numberDiff line numberDiff line change
@@ -208,15 +208,15 @@ export function readSomeEvent(sinkOrBuf: SinkOrBuf): SomeEvent {
208208
case 1:
209209
return SomeEvent.UnnamedSingle(
210210
readF32(sink),
211-
);
211+
);
212212
case 2:
213213
return SomeEvent.UnnamedOptVec(
214214
readOption(readTypedArray(Uint8Array))(sink),
215-
);
215+
);
216216
case 3:
217217
return SomeEvent.UnnamedSingleUnitEnum(
218218
readOption(readSeq(readUnitEnum))(sink),
219-
);
219+
);
220220
case 4:
221221
return SomeEvent.UnnamedMultiple(
222222
readU8(sink),
@@ -232,24 +232,24 @@ export function readSomeEvent(sinkOrBuf: SinkOrBuf): SomeEvent {
232232
readUSize(sink),
233233
readISize(sink),
234234
readBool(sink),
235-
);
235+
);
236236
case 5:
237237
return SomeEvent.Named({
238238
length: readUSize(sink),
239239
interval: readF64(sink),
240-
});
240+
});
241241
case 6:
242242
return SomeEvent.UnnamedWithStruct(
243243
readNamedStruct(sink),
244-
);
244+
);
245245
case 7:
246246
return SomeEvent.UnnamedHashMap(
247247
readOption(readMap(readString, readOption(readUnitEnum)))(sink),
248-
);
248+
);
249249
case 8:
250250
return SomeEvent.NamedStruct({
251251
inner: readNamedStruct(sink),
252-
});
252+
});
253253
default:
254254
throw new Error(`'${value}' is invalid value for enum 'SomeEvent'`);
255255
}

Diff for: tests/tests.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,7 @@ function test(buffer: Buffer): api.Sink {{
124124
}
125125

126126
#[test]
127-
fn named_struct() {
127+
fn named_struct_with_tuple() {
128128
generate_and_run(
129129
NamedStruct {
130130
zero: Some(28),
@@ -256,7 +256,7 @@ function test(buffer: Buffer): api.Sink {{
256256
SomeEvent::UnnamedHashMap(Some(
257257
vec![
258258
("One".to_string(), Some(UnitEnum::One)),
259-
("Two".to_string(), Some(UnitEnum::Two)),
259+
("Two".to_string(), None),
260260
("Three".to_string(), Some(UnitEnum::Three)),
261261
]
262262
.into_iter()
@@ -267,7 +267,7 @@ function test(buffer: Buffer): api.Sink {{
267267
let expected = api.SomeEvent.UnnamedHashMap(
268268
new Map([
269269
['One', api.UnitEnum.One],
270-
['Two', api.UnitEnum.Two],
270+
['Two', undefined],
271271
['Three', api.UnitEnum.Three],
272272
])
273273
);

0 commit comments

Comments
 (0)