Skip to content

Commit

Permalink
feat: add $.spread (#58)
Browse files Browse the repository at this point in the history
add $.spread
  • Loading branch information
tjjfvi committed Jun 8, 2022
1 parent 308c922 commit 1a9d7b4
Show file tree
Hide file tree
Showing 6 changed files with 66 additions and 0 deletions.
3 changes: 3 additions & 0 deletions fixtures.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ pub mod object_fixtures;
#[path = "./result/fixtures.rs"]
pub mod result_fixtures;

#[path = "./spread/fixtures.rs"]
pub mod spread_fixtures;

#[path = "./str/fixtures.rs"]
pub mod str_fixtures;

Expand Down
1 change: 1 addition & 0 deletions mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export * from "./object/codec.ts";
export * from "./option/codec.ts";
export * from "./option/optionBool/codec.ts";
export * from "./result/codec.ts";
export * from "./spread/codec.ts";
export * from "./str/codec.ts";
export * from "./transform/codec.ts";
export * from "./tuple/codec.ts";
Expand Down
12 changes: 12 additions & 0 deletions spread/__snapshots__/test.ts.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
export const snapshot = {};

snapshot[`object { _tag: "a", bar: 123 } 1`] = `
00
7b
`;

snapshot[`object { _tag: "b", x: 0, bar: 123 } 1`] = `
01
00
7b
`;
14 changes: 14 additions & 0 deletions spread/codec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { Codec, createCodec } from "../common.ts";

export function spread<A, B>($a: Codec<A>, $b: Codec<B>) {
return createCodec<A & B>({
_staticSize: $a._staticSize + $b._staticSize,
_encode(buffer, value) {
$a._encode(buffer, value);
$b._encode(buffer, value);
},
_decode(buffer) {
return { ...$a._decode(buffer), ...$b._decode(buffer) };
},
});
}
19 changes: 19 additions & 0 deletions spread/fixtures.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
use parity_scale_codec::Encode;

#[derive(Encode)]
enum Foo {
A,
B(u8),
}

#[derive(Encode)]
struct Bar(u8);

#[derive(Encode)]
struct Foobar(Foo, Bar);

#[rustfmt::skip]
crate::fixtures!(
Foobar(Foo::A, Bar(123)),
Foobar(Foo::B(0), Bar(123)),
);
17 changes: 17 additions & 0 deletions spread/test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import * as $ from "../mod.ts";
import { testCodec } from "../test-util.ts";

const $foo = $.taggedUnion(
"_tag",
["a"],
["b", ["x", $.u8]],
);

const $bar = $.object(["bar", $.u8]);

const $foobar = $.spread($foo, $bar);

testCodec("object", $foobar, [
{ _tag: "a", bar: 123 },
{ _tag: "b", x: 0, bar: 123 },
]);

0 comments on commit 1a9d7b4

Please sign in to comment.