= None;
let encoded_none = borsh::to_vec(&none_value).unwrap();
assert_eq!(encoded_none, vec![0]); // Just the 0 discriminant
// String encoding
let text = String::from("hello");
let encoded_str = borsh::to_vec(&text).unwrap();
// 4 bytes length (5) + 5 bytes "hello"
assert_eq!(encoded_str, vec![5, 0, 0, 0, b'h', b'e', b'l', b'l', b'o']);
// Unicode string
let unicode = String::from("你好");
let encoded_unicode = borsh::to_vec(&unicode).unwrap();
println!("Unicode bytes: {:?}", encoded_unicode);
// Length is 6 (UTF-8 bytes for two Chinese characters)
assert_eq!(encoded_unicode[0..4], [6, 0, 0, 0]);
}
```
--------------------------------
### Configure highlight.js with useBR
Source: https://github.com/near/borsh/blob/master/docs/highlight/README.md
Configure highlight.js to use the `
` tag for line breaks when not using containers that preserve line breaks, such as ``. This ensures proper formatting for highlighted code.
```javascript
hljs.configure({useBR: true});
document.querySelectorAll('div.code').forEach((block) => {
hljs.highlightBlock(block);
});
```
--------------------------------
### Import Stylesheet (CommonJS)
Source: https://github.com/near/borsh/blob/master/docs/highlight/README.md
Import a Highlight.js theme stylesheet directly into your CommonJS module if your build tool processes CSS from JavaScript.
```javascript
import hljs from 'highlight.js/lib/highlight';
import 'highlight.js/styles/github.css';
```
--------------------------------
### Import Specific Language (CommonJS)
Source: https://github.com/near/borsh/blob/master/docs/highlight/README.md
Import only the Highlight.js core library and a specific language module for more efficient builds in a CommonJS environment.
```javascript
import hljs from 'highlight.js/lib/highlight';
import javascript from 'highlight.js/lib/languages/javascript';
hljs.registerLanguage('javascript', javascript);
```
--------------------------------
### Run Highlighting in Web Worker
Source: https://github.com/near/borsh/blob/master/docs/highlight/README.md
Use a web worker to perform syntax highlighting without freezing the browser. The main script sends code to the worker, and the worker returns the highlighted HTML.
```javascript
addEventListener('load', () => {
const code = document.querySelector('#code');
const worker = new Worker('worker.js');
worker.onmessage = (event) => { code.innerHTML = event.data; }
worker.postMessage(code.textContent);
});
```
```javascript
onmessage = (event) => {
importScripts('/highlight.pack.js');
const result = self.hljs.highlightAuto(event.data);
postMessage(result.value);
};
```
--------------------------------
### Serialize and Deserialize Structs with borsh-go
Source: https://context7.com/near/borsh/llms.txt
This Go snippet shows how to use the borsh-go library for serialization and deserialization of structs. It utilizes struct tags for mapping fields.
```go
package main
import (
"fmt"
"github.com/near/borsh-go"
)
type Account struct {
ID uint64 `borsh_skip:"false"`
Name string
Balance [16]byte // u128 represented as byte array
IsActive bool
}
func main() {
account := Account{
ID: 12345,
Name: "alice",
Balance: [16]byte{0, 0, 64, 122, 16, 243, 90, 0, 0, 0, 0, 0, 0, 0, 0, 0},
IsActive: true,
}
// Serialize
encoded, err := borsh.Serialize(account)
if err != nil {
panic(err)
}
fmt.Printf("Encoded: %x\n", encoded)
// Deserialize
var decoded Account
err = borsh.Deserialize(&decoded, encoded)
if err != nil {
panic(err)
}
fmt.Printf("ID: %d\n", decoded.ID)
fmt.Printf("Name: %s\n", decoded.Name)
fmt.Printf("Active: %t\n", decoded.IsActive)
// Output:
// ID: 12345
// Name: alice
// Active: true
}
```
--------------------------------
### Rust Struct Serialization and Deserialization
Source: https://context7.com/near/borsh/llms.txt
Demonstrates how to derive BorshSerialize and BorshDeserialize traits for custom Rust structs. Use this for creating deterministic byte representations of your data structures.
```rust
use borsh::{BorshSerialize, BorshDeserialize};
#[derive(BorshSerialize, BorshDeserialize, PartialEq, Debug)]
struct Account {
id: u64,
name: String,
balance: u128,
is_active: bool,
}
fn main() {
// Create an account
let account = Account {
id: 12345,
name: "alice".to_string(),
balance: 1_000_000_000_000_000_000_000_000, // 1e24
is_active: true,
};
// Serialize to bytes
let encoded: Vec = borsh::to_vec(&account).unwrap();
println!("Serialized bytes: {:?}", encoded);
// Output: Serialized bytes: [57, 48, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 97, 108, 105, 99, 101, 0, 0, 64, 122, 16, 243, 90, 0, 0, 0, 0, 0, 0, 0, 0, 1]
// Deserialize back to struct
let decoded: Account = borsh::from_slice(&encoded).unwrap();
assert_eq!(account, decoded);
println!("Decoded account: {:?}", decoded);
// Output: Decoded account: Account { id: 12345, name: "alice", balance: 1000000000000000000000000, is_active: true }
}
```
--------------------------------
### Rust Collection Serialization (Vec, HashMap, HashSet)
Source: https://context7.com/near/borsh/llms.txt
Illustrates serialization of dynamic collections like Vec and HashMap. Borsh prefixes collections with a u32 length and sorts HashMaps lexicographically by key for deterministic output.
```rust
use borsh::{BorshSerialize, BorshDeserialize};
use std::collections::HashMap;
#[derive(BorshSerialize, BorshDeserialize, Debug)]
struct Wallet {
owner: String,
tokens: Vec,
balances: HashMap,
}
fn main() {
let mut balances = HashMap::new();
balances.insert("NEAR".to_string(), 100_000_000_000_000_000_000_000_000);
balances.insert("USDC".to_string(), 50_000_000);
let wallet = Wallet {
owner: "alice.near".to_string(),
tokens: vec!["NEAR".to_string(), "USDC".to_string(), "wETH".to_string()],
balances,
};
let encoded = borsh::to_vec(&wallet).unwrap();
println!("Wallet serialized size: {} bytes", encoded.len());
// Deserialize
let decoded: Wallet = borsh::from_slice(&encoded).unwrap();
println!("Owner: {}", decoded.owner);
println!("Tokens: {:?}", decoded.tokens);
println!("NEAR balance: {:?}", decoded.balances.get("NEAR"));
// Output:
// Wallet serialized size: 80 bytes
// Owner: alice.near
// Tokens: ["NEAR", "USDC", "wETH"]
// NEAR balance: Some(100000000000000000000000000)
}
```
--------------------------------
### Serialize HashSet Type
Source: https://github.com/near/borsh/blob/master/docs/index.html
Serializes a HashSet by first writing its length as a u32, then serializing each element after sorting them lexicographically.
```pseudocode
hashset: "HashSet<" ident ">"
repr(x.len() as u32)
for el in x.sorted() {
repr(el as ident)
}
```
--------------------------------
### Rust Struct Serialization and Deserialization with Borsh
Source: https://github.com/near/borsh/blob/master/docs/index.html
Demonstrates serializing a Rust struct to a byte vector and deserializing it back using Borsh. Ensure the struct derives `BorshSerialize` and `BorshDeserialize`.
```rust
use borsh::{BorshSerialize, BorshDeserialize};
#[derive(BorshSerialize, BorshDeserialize, PartialEq, Debug)]
struct A {
x: u64,
y: String,
}
#[test]
fn test_simple_struct() {
let a = A {
x: 3301,
y: "liber primus".to_string(),
};
let encoded_a = borsh::to_vec(a).unwrap();
let decoded_a = borsh::from_slice::(&encoded_a).unwrap();
assert_eq!(a, decoded_a);
}
```
--------------------------------
### Serialize and Deserialize Structs with borsh-construct (Python)
Source: https://context7.com/near/borsh/llms.txt
This Python snippet demonstrates serializing and deserializing data structures using borsh-construct. It supports basic types, strings, and vectors.
```python
from borsh_construct import CStruct, String, U64, U128, Bool, Vec
# Define schema
Account = CStruct(
"id" / U64,
"name" / String,
"balance" / U128,
"is_active" / Bool,
)
# Serialize
account_data = {
"id": 12345,
"name": "alice",
"balance": 1_000_000_000_000_000_000_000_000,
"is_active": True,
}
encoded = Account.build(account_data)
print(f"Encoded: {encoded.hex()}")
# Deserialize
decoded = Account.parse(encoded)
print(f"ID: {decoded.id}")
print(f"Name: {decoded.name}")
print(f"Balance: {decoded.balance}")
print(f"Active: {decoded.is_active}")
# Output:
# ID: 12345
# Name: alice
# Balance: 1000000000000000000000000
# Active: True
# Working with vectors
TokenList = CStruct(
"tokens" / Vec(String),
)
tokens = {"tokens": ["NEAR", "USDC", "wETH"]}
encoded_tokens = TokenList.build(tokens)
decoded_tokens = TokenList.parse(encoded_tokens)
print(f"Tokens: {decoded_tokens.tokens}")
# Output: Tokens: ['NEAR', 'USDC', 'wETH']
```
--------------------------------
### Serialize String Type
Source: https://github.com/near/borsh/blob/master/docs/index.html
Serializes a String by first writing its UTF-8 encoded length as a u32, followed by the UTF-8 encoded bytes of the string.
```pseudocode
string_type: "String"
encoded = utf8_encoding(x) as Vec
repr(encoded.len() as u32)
repr(encoded as Vec)
```
--------------------------------
### Plain Text Code Block
Source: https://github.com/near/borsh/blob/master/docs/highlight/README.md
Use the `plaintext` class to make arbitrary text look like code without applying any highlighting. This is useful for displaying code snippets that are not meant to be highlighted.
```html
...
```
--------------------------------
### Serialize HashMap Type
Source: https://github.com/near/borsh/blob/master/docs/index.html
Serializes a HashMap by first writing its length as a u32, then serializing each key-value pair after sorting them lexicographically by key.
```pseudocode
hashmap: "HashMap<" ident0, ident1 ">"
repr(x.len() as u32)
for (k, v) in x.sorted_by_key() {
repr(k as ident0)
repr(v as ident1)
}
```
--------------------------------
### Serialize Option Type
Source: https://github.com/near/borsh/blob/master/docs/index.html
Serializes an Option by writing a u8 indicating presence (1) or absence (0), followed by the contained value if present.
```pseudocode
option_type: "Option<" ident '>'
if x.is_some() {
repr(1 as u8)
repr(x.unwrap() as ident)
} else {
repr(0 as u8)
}
```
--------------------------------
### Include Language Submodes in Highlight.js
Source: https://github.com/near/borsh/blob/master/docs/highlight/CHANGES.md
Demonstrates how to include language submodes directly within the 'contains' array for auxiliary modes. These modes may not have a 'className' and thus won't generate a separate span.
```javascript
contains: [
'string',
'number',
{
begin: '\n',
end: hljs.IMMEDIATE_RE
}
]
```
--------------------------------
### Specify Language Class for Highlight.js
Source: https://github.com/near/borsh/blob/master/docs/highlight/README.md
Manually specify the language for a code block by adding a language class to the `` tag. This is useful when automatic detection fails or is inaccurate.
```html
...
```
--------------------------------
### Serialize Dynamic-Size Array (Vec) Type
Source: https://github.com/near/borsh/blob/master/docs/index.html
Serializes a dynamic-size array (Vec) by first writing its length as a u32, followed by each element serialized according to its type.
```pseudocode
vec_type: "Vec<" ident '>'
repr(len() as u32)
for el in x
repr(el as ident)
```