Don Newton | 379ae25 | 2019-04-01 12:17:06 -0400 | [diff] [blame^] | 1 | // Copyright (C) MongoDB, Inc. 2017-present. |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may |
| 4 | // not use this file except in compliance with the License. You may obtain |
| 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 |
| 6 | |
| 7 | package wiremessage |
| 8 | |
| 9 | import ( |
| 10 | "bytes" |
| 11 | "errors" |
| 12 | |
| 13 | "github.com/mongodb/mongo-go-driver/bson" |
| 14 | ) |
| 15 | |
| 16 | func readInt32(b []byte, pos int32) int32 { |
| 17 | return (int32(b[pos+0])) | (int32(b[pos+1]) << 8) | (int32(b[pos+2]) << 16) | (int32(b[pos+3]) << 24) |
| 18 | } |
| 19 | |
| 20 | func readCString(b []byte, pos int32) (string, error) { |
| 21 | null := bytes.IndexByte(b[pos:], 0x00) |
| 22 | if null == -1 { |
| 23 | return "", errors.New("invalid cstring") |
| 24 | } |
| 25 | return string(b[pos : int(pos)+null]), nil |
| 26 | } |
| 27 | |
| 28 | func readInt64(b []byte, pos int32) int64 { |
| 29 | return (int64(b[pos+0])) | (int64(b[pos+1]) << 8) | (int64(b[pos+2]) << 16) | (int64(b[pos+3]) << 24) | (int64(b[pos+4]) << 32) | |
| 30 | (int64(b[pos+5]) << 40) | (int64(b[pos+6]) << 48) | (int64(b[pos+7]) << 56) |
| 31 | |
| 32 | } |
| 33 | |
| 34 | // readDocument will attempt to read a bson.Reader from the given slice of bytes |
| 35 | // from the given position. |
| 36 | func readDocument(b []byte, pos int32) (bson.Raw, int, Error) { |
| 37 | if int(pos)+4 > len(b) { |
| 38 | return nil, 0, Error{Message: "document too small to be valid"} |
| 39 | } |
| 40 | size := int(readInt32(b, int32(pos))) |
| 41 | if int(pos)+size > len(b) { |
| 42 | return nil, 0, Error{Message: "document size is larger than available bytes"} |
| 43 | } |
| 44 | if b[int(pos)+size-1] != 0x00 { |
| 45 | return nil, 0, Error{Message: "document invalid, last byte is not null"} |
| 46 | } |
| 47 | // TODO(GODRIVER-138): When we add 3.0 support, alter this so we either do one larger make or use a pool. |
| 48 | rdr := make(bson.Raw, size) |
| 49 | copy(rdr, b[pos:int(pos)+size]) |
| 50 | return rdr, size, Error{Type: ErrNil} |
| 51 | } |