Skip to content

Commit

Permalink
String
Browse files Browse the repository at this point in the history
  • Loading branch information
Rigidity committed Sep 25, 2024
1 parent 10e1cbe commit db8eb4b
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 0 deletions.
8 changes: 8 additions & 0 deletions napi/__test__/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,14 @@ test("atom roundtrip", (t) => {
t.true(compareBytes(clvm.atom(atom), expected));
});

test("string roundtrip", (t) => {
const clvm = new ClvmAllocator();

const expected = "hello world";
const atom = clvm.newString(expected);
t.is(clvm.string(atom), expected);
});

test("small number roundtrip", (t) => {
const clvm = new ClvmAllocator();

Expand Down
2 changes: 2 additions & 0 deletions napi/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,12 +98,14 @@ export declare class ClvmAllocator {
newList(values: Array<ClvmPtr>): ClvmPtr
newPair(first: ClvmPtr, rest: ClvmPtr): ClvmPtr
newAtom(value: Uint8Array): ClvmPtr
newString(value: string): ClvmPtr
newSmallNumber(value: number): ClvmPtr
newBigInt(value: bigint): ClvmPtr
list(ptr: ClvmPtr): Array<ClvmPtr>
pair(ptr: ClvmPtr): Pair | null
atom(ptr: ClvmPtr): Uint8Array | null
atomLength(ptr: ClvmPtr): number | null
string(ptr: ClvmPtr): string | null
smallNumber(ptr: ClvmPtr): number | null
bigInt(ptr: ClvmPtr): bigint | null
}
Expand Down
17 changes: 17 additions & 0 deletions napi/src/clvm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,15 @@ impl ClvmAllocator {
Ok(ClvmPtr(ptr))
}

#[napi]
pub fn new_string(&mut self, value: String) -> Result<ClvmPtr> {
let ptr = self
.0
.new_atom(value.as_bytes())
.map_err(|error| Error::from_reason(error.to_string()))?;
Ok(ClvmPtr(ptr))
}

#[napi]
pub fn new_small_number(&mut self, value: u32) -> Result<ClvmPtr> {
// TODO: Upstream a better check to clvmr?
Expand Down Expand Up @@ -227,6 +236,14 @@ impl ClvmAllocator {
}
}

#[napi]
pub fn string(&self, ptr: &ClvmPtr) -> Option<String> {
match self.0.sexp(ptr.0) {
SExp::Atom => String::from_utf8(self.0.atom(ptr.0).as_ref().to_vec()).ok(),
SExp::Pair(..) => None,
}
}

#[napi]
pub fn small_number(&self, ptr: &ClvmPtr) -> Option<u32> {
match self.0.sexp(ptr.0) {
Expand Down

0 comments on commit db8eb4b

Please sign in to comment.