 
 CONSTANT: MSG-HEADER-SIZE 16
 
+SYMBOL: msg-bytes-read 
+
+: bytes-read> ( -- integer )
+    msg-bytes-read get ; inline
+
+: >bytes-read ( integer -- )
+    msg-bytes-read set ; inline
+
+: change-bytes-read ( integer -- )
+    bytes-read> [ 0 ] unless* + >bytes-read ; inline
+
 : write-byte ( byte -- ) <char> write ; inline
 : write-int32 ( int -- ) <int> write ; inline
 : write-double ( real -- ) <double> write ; inline
 : write-cstring ( string -- ) utf8 string>alien write ; inline
 : write-longlong ( object -- ) <longlong> write ; inline
 
-: read-int32 ( -- int32 ) 4 read *int ; inline
-: read-longlong ( -- longlong ) 8 read *longlong ; inline
-: read-byte-raw ( -- byte-raw ) 1 read ; inline
+: read-int32 ( -- int32 ) 4 [ read *int ] [ change-bytes-read ] bi ; inline
+: read-longlong ( -- longlong ) 8 [ read *longlong ] [ change-bytes-read ] bi ; inline
+: read-byte-raw ( -- byte-raw ) 1 [ read ] [ change-bytes-read ] bi ; inline
 : read-byte ( -- byte ) read-byte-raw *char ; inline
 
 : (read-cstring) ( acc -- acc )


: read-message ( -- message )
    mdb-msg new
    read-header
    [ ] [ opcode>> ] bi (read-message) ;


USING: io io.encodings.utf8 io.encodings.binary alien.c-types alien.strings math
bson.writer sequences kernel accessors io.streams.byte-array fry generalizations
combinators bson.reader sequences tools.walker assocs strings linked-assocs namespaces ;

IN: mongodb.msg

