Skip to content

Commit

Permalink
Merge pull request #256 from pyropy/feat/memory
Browse files Browse the repository at this point in the history
feat: memory multiaddrs
  • Loading branch information
MarcoPolo authored Oct 28, 2024
2 parents 414c602 + 94c19d5 commit 04c33d5
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 0 deletions.
2 changes: 2 additions & 0 deletions multiaddr_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ func TestConstructFails(t *testing.T) {
"/ip4/1.2.3.4/tcp/80/unix",
"/ip4/1.2.3.4/tcp/-1",
"/ip4/127.0.0.1/tcp/9090/http/p2p-webcrt-direct",
fmt.Sprintf("/memory/%d1", uint64(1<<63)),
"/",
"",
"/p2p/QmxoHT6iViN5xAjoz1VZ553cL31U9F94ht3QvWR1FrEbZY", // sha256 multihash with digest len > 32
Expand Down Expand Up @@ -197,6 +198,7 @@ var good = []string{
"/http-path/foo",
"/ip4/127.0.0.1/tcp/0/p2p/12D3KooWCryG7Mon9orvQxcS1rYZjotPgpwoJNHHKcLLfE4Hf5mV/http-path/foo",
"/ip4/127.0.0.1/tcp/443/tls/sni/example.com/http/http-path/foo",
"/memory/4",
}

func TestConstructSucceeds(t *testing.T) {
Expand Down
10 changes: 10 additions & 0 deletions protocols.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ const (
P_PLAINTEXTV2 = 7367777
P_WEBRTC_DIRECT = 280
P_WEBRTC = 281
P_MEMORY = 777
)

var (
Expand Down Expand Up @@ -281,6 +282,14 @@ var (
Code: P_WEBRTC,
VCode: CodeToVarint(P_WEBRTC),
}

protoMemory = Protocol{
Name: "memory",
Code: P_MEMORY,
VCode: CodeToVarint(P_MEMORY),
Size: 64,
Transcoder: TranscoderMemory,
}
)

func init() {
Expand Down Expand Up @@ -322,6 +331,7 @@ func init() {
protoPlaintextV2,
protoWebRTCDirect,
protoWebRTC,
protoMemory,
} {
if err := AddProtocol(p); err != nil {
panic(err)
Expand Down
29 changes: 29 additions & 0 deletions transcoders.go
Original file line number Diff line number Diff line change
Expand Up @@ -489,3 +489,32 @@ func validateHTTPPath(b []byte) error {
}
return nil // We can represent any byte slice when we escape it.
}

var TranscoderMemory = NewTranscoderFromFunctions(memoryStB, memoryBtS, memoryValidate)

func memoryStB(s string) ([]byte, error) {
z, err := strconv.ParseUint(s, 10, 64)
if err != nil {
return nil, err
}
buf := make([]byte, 8)
binary.BigEndian.PutUint64(buf, z)
return buf, nil
}

func memoryBtS(b []byte) (string, error) {
if len(b) != 8 {
return "", fmt.Errorf("expected uint64, only found %d bits", len(b)*8)
}
z := binary.BigEndian.Uint64(b)
return strconv.FormatUint(z, 10), nil
}

func memoryValidate(b []byte) error {
// Ensure the byte array is exactly 8 bytes long for a uint64 in big-endian format
if len(b) != 8 {
return errors.New("invalid length: must be exactly 8 bytes")
}

return nil
}

0 comments on commit 04c33d5

Please sign in to comment.