Skip to content

Commit 04c33d5

Browse files
authored
Merge pull request #256 from pyropy/feat/memory
feat: memory multiaddrs
2 parents 414c602 + 94c19d5 commit 04c33d5

File tree

3 files changed

+41
-0
lines changed

3 files changed

+41
-0
lines changed

multiaddr_test.go

+2
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,7 @@ func TestConstructFails(t *testing.T) {
8585
"/ip4/1.2.3.4/tcp/80/unix",
8686
"/ip4/1.2.3.4/tcp/-1",
8787
"/ip4/127.0.0.1/tcp/9090/http/p2p-webcrt-direct",
88+
fmt.Sprintf("/memory/%d1", uint64(1<<63)),
8889
"/",
8990
"",
9091
"/p2p/QmxoHT6iViN5xAjoz1VZ553cL31U9F94ht3QvWR1FrEbZY", // sha256 multihash with digest len > 32
@@ -197,6 +198,7 @@ var good = []string{
197198
"/http-path/foo",
198199
"/ip4/127.0.0.1/tcp/0/p2p/12D3KooWCryG7Mon9orvQxcS1rYZjotPgpwoJNHHKcLLfE4Hf5mV/http-path/foo",
199200
"/ip4/127.0.0.1/tcp/443/tls/sni/example.com/http/http-path/foo",
201+
"/memory/4",
200202
}
201203

202204
func TestConstructSucceeds(t *testing.T) {

protocols.go

+10
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ const (
4141
P_PLAINTEXTV2 = 7367777
4242
P_WEBRTC_DIRECT = 280
4343
P_WEBRTC = 281
44+
P_MEMORY = 777
4445
)
4546

4647
var (
@@ -281,6 +282,14 @@ var (
281282
Code: P_WEBRTC,
282283
VCode: CodeToVarint(P_WEBRTC),
283284
}
285+
286+
protoMemory = Protocol{
287+
Name: "memory",
288+
Code: P_MEMORY,
289+
VCode: CodeToVarint(P_MEMORY),
290+
Size: 64,
291+
Transcoder: TranscoderMemory,
292+
}
284293
)
285294

286295
func init() {
@@ -322,6 +331,7 @@ func init() {
322331
protoPlaintextV2,
323332
protoWebRTCDirect,
324333
protoWebRTC,
334+
protoMemory,
325335
} {
326336
if err := AddProtocol(p); err != nil {
327337
panic(err)

transcoders.go

+29
Original file line numberDiff line numberDiff line change
@@ -489,3 +489,32 @@ func validateHTTPPath(b []byte) error {
489489
}
490490
return nil // We can represent any byte slice when we escape it.
491491
}
492+
493+
var TranscoderMemory = NewTranscoderFromFunctions(memoryStB, memoryBtS, memoryValidate)
494+
495+
func memoryStB(s string) ([]byte, error) {
496+
z, err := strconv.ParseUint(s, 10, 64)
497+
if err != nil {
498+
return nil, err
499+
}
500+
buf := make([]byte, 8)
501+
binary.BigEndian.PutUint64(buf, z)
502+
return buf, nil
503+
}
504+
505+
func memoryBtS(b []byte) (string, error) {
506+
if len(b) != 8 {
507+
return "", fmt.Errorf("expected uint64, only found %d bits", len(b)*8)
508+
}
509+
z := binary.BigEndian.Uint64(b)
510+
return strconv.FormatUint(z, 10), nil
511+
}
512+
513+
func memoryValidate(b []byte) error {
514+
// Ensure the byte array is exactly 8 bytes long for a uint64 in big-endian format
515+
if len(b) != 8 {
516+
return errors.New("invalid length: must be exactly 8 bytes")
517+
}
518+
519+
return nil
520+
}

0 commit comments

Comments
 (0)