nim-libp2p/libp2p/muxers/mplex/coder.nim

51 lines
1.5 KiB
Nim
Raw Normal View History

2019-09-04 03:08:51 +00:00
## Nim-LibP2P
## Copyright (c) 2018 Status Research & Development GmbH
## Licensed under either of
## * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE))
## * MIT license ([LICENSE-MIT](LICENSE-MIT))
## at your option.
## This file may not be copied, modified, or distributed except according to
## those terms.
import chronos
2019-09-06 06:51:19 +00:00
import types,
../../connection,
../../varint,
../../vbuffer,
../../stream/lpstream,
nimcrypto/utils
2019-09-04 03:08:51 +00:00
2019-09-06 21:27:55 +00:00
type
Phase = enum Header, Size
2019-09-04 03:08:51 +00:00
proc readHeader*(conn: Connection): Future[(uint, MessageType)] {.async, gcsafe.} =
var
header: uint
length: int
res: VarintStatus
var buffer = newSeq[byte](10)
try:
for i in 0..<len(buffer):
await conn.readExactly(addr buffer[i], 1)
res = LP.getUVarint(buffer.toOpenArray(0, i), length, header)
if res == VarintStatus.Success:
2019-09-06 21:27:55 +00:00
let (id, msg) = (header shr 3, MessageType(header and 0x7))
2019-09-04 03:08:51 +00:00
return (header shr 3, MessageType(header and 0x7))
if res != VarintStatus.Success:
buffer.setLen(0)
return
2019-09-06 21:27:55 +00:00
except TransportIncompleteError:
2019-09-04 03:08:51 +00:00
buffer.setLen(0)
2019-09-06 21:27:55 +00:00
raise newLPStreamIncompleteError()
2019-09-04 03:08:51 +00:00
proc writeHeader*(conn: Connection,
id: int,
msgType: MessageType,
2019-09-06 06:51:19 +00:00
size: int = 0) {.async, gcsafe.} =
2019-09-04 03:08:51 +00:00
## write lenght prefixed
var buf = initVBuffer()
2019-09-06 21:27:55 +00:00
buf.writeVarint((id.uint shl 3) or msgType.uint)
buf.writeVarint(size.uint) # size should be always sent
2019-09-04 03:08:51 +00:00
buf.finish()
2019-09-06 21:27:55 +00:00
await conn.write(buf.buffer)