├── .gitignore ├── .travis.yml ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── bulk.yaml ├── src ├── buf.rs ├── lib.rs └── range.rs └── vagga.yaml /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /Cargo.lock 3 | /.vagga 4 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | dist: trusty 3 | language: rust 4 | 5 | cache: 6 | - cargo 7 | 8 | before_cache: 9 | - rm -r $TRAVIS_BUILD_DIR/target/debug 10 | 11 | jobs: 12 | include: 13 | - os: linux 14 | rust: stable 15 | - os: linux 16 | rust: beta 17 | - os: linux 18 | rust: nightly 19 | 20 | # deploy 21 | - stage: publish 22 | os: linux 23 | rust: stable 24 | env: 25 | # CARGO_TOKEN 26 | - secure: "ZFVUuLLY6PZwc8kjUfGeEK8rrWa01sXEkB3APIxTnQQSP/VPkNcIRZtIjY3KPYwWBZqrrICclEzMJ7llgk58Sk8rfLI33mk4br1QFq+R0eCeW4YnDu7jTpZqjyXhWwStzE83RbXMqdElMnOntrQQLp2t2qNfqcZ58T9knt2qJfNM5MUNqN3ytP30as+nYRBSvv3mrYqKTe24tj4YwfUMFNeVr48FUPo99kOXeRfhaVpJVlm/id7mnYVq3VoXexTLMT/TTq5r5838SxMkl+8VD34wPerNrWsHyFunbn+nl/0W51iJ12+KxBjQb2FmJIkerZREkOOIkcdk8d3qeEIFTOlW7aSCapMDehVj+4/UtvnIXb1MClxphKFC6+Rpy52zzfufh7IJmjDzwzCUfGvTqbGWsghwQzxRp4yAoN8x0JQSRi6Zes5N0njZ7gFEdihBkwfmc/XYyOyGgpwkpOeHd/aqLT8kpZGDhgevzQtBleMgJuC5bob4+jvVAF3Q2NP6h4AriUvOgH14aCaW1/EAV4TUkUAvDIe5nGb6rT6WgBYjFInMD/Ny5dEENg6wDfqX3OAmHDPaYlIcLnb7XaRI/s9t2bSw/6kRRVlkgM4dwEtptD7u8MzF190m22fiGWCy7LvXjI2xME3kQAxZnElV+RNK7j5qaByL4tqsyiBh/7E=" 27 | install: true 28 | script: true 29 | 30 | deploy: 31 | - provider: script 32 | script: 'cargo publish --verbose --token=$CARGO_TOKEN' 33 | on: 34 | tags: true 35 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "netbuf" 3 | description = """ 4 | The simple to use, growable, contiguous buffer object with right 5 | assumptions and interface. Tuned for using it for network buffers. 6 | """ 7 | readme = "README.md" 8 | keywords = ["buf", "netbuf", "network", "buffer", "vec"] 9 | categories = ["network-programming", "memory-management"] 10 | version = "0.4.1" 11 | authors = ["Paul Colomiets "] 12 | license = "MIT/Apache-2.0" 13 | documentation = "http://tailhook.github.io/netbuf/" 14 | repository = "http://github.com/tailhook/netbuf" 15 | 16 | [dev-dependencies] 17 | mockstream = "0.0.2" 18 | 19 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2015 Paul Colomiets 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in 11 | all copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | THE SOFTWARE. 20 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Netbuf 2 | ====== 3 | 4 | [Documentation](https://docs.rs/netbuf) | 5 | [Github](https://github.com/tailhook/netbuf) | 6 | [Crate](https://crates.io/crates/netbuf) 7 | 8 | The network buffer for usage in asynchronous network applications. Has right 9 | interface for reading from network into the ``Buf`` and for parsing packets 10 | directly from it. It also has capacity management tuned for network application 11 | (i.e. it starts growing fast, but deallocated for idle connections). 12 | 13 | 14 | License 15 | ======= 16 | 17 | Licensed under either of 18 | 19 | * Apache License, Version 2.0, 20 | (./LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0) 21 | * MIT license (./LICENSE-MIT or http://opensource.org/licenses/MIT) 22 | at your option. 23 | 24 | Contribution 25 | ------------ 26 | 27 | Unless you explicitly state otherwise, any contribution intentionally 28 | submitted for inclusion in the work by you, as defined in the Apache-2.0 29 | license, shall be dual licensed as above, without any additional terms or 30 | conditions. 31 | -------------------------------------------------------------------------------- /bulk.yaml: -------------------------------------------------------------------------------- 1 | minimum-bulk: v0.4.5 2 | 3 | versions: 4 | 5 | - file: Cargo.toml 6 | block-start: ^\[package\] 7 | block-end: ^\[.*\] 8 | regex: ^version\s*=\s*"(\S+)" 9 | -------------------------------------------------------------------------------- /src/buf.rs: -------------------------------------------------------------------------------- 1 | use std::ptr::{copy_nonoverlapping, copy}; 2 | use std::ops::{Index, IndexMut, RangeFrom, RangeTo, RangeFull, Range}; 3 | use std::cmp::{min, max}; 4 | use std::io::{Read, Write, Result}; 5 | use std::fmt::{self, Debug}; 6 | use std::mem::swap; 7 | 8 | use range::RangeArgument; 9 | 10 | const READ_MIN: usize = 4096; 11 | const ALLOC_MIN: usize = 16384; 12 | 13 | /// 14 | /// A buffer object to be used for reading from network 15 | /// 16 | /// Assumptions: 17 | /// 18 | /// 1. Buffer needs to be growable as sometimes requests are large 19 | /// 20 | /// 2. Buffer should deallocate when empty as 21 | /// most of the time connections are idle 22 | /// 23 | /// a. Deallocations are cheap as we have a cool memory allocator 24 | /// (jemalloc) 25 | /// 26 | /// b. First allocation should be big (i.e. kilobytes not few bytes) 27 | /// 28 | /// 3. Should be easy to peek and get a slice as it makes packet parsing easy 29 | /// 30 | /// 4. Cheap removing bytes at the start of the buf 31 | /// 32 | pub struct Buf { 33 | data: Option>, 34 | consumed: usize, 35 | remaining: usize, 36 | } 37 | 38 | 39 | // TODO(tailhook) use std::slice::bytes::copy_memory; 40 | fn copy_memory(src: &[u8], dst: &mut [u8]) { 41 | assert!(src.len() == dst.len()); 42 | unsafe { 43 | copy_nonoverlapping(src.as_ptr(), dst.as_mut_ptr(), dst.len()); 44 | } 45 | } 46 | 47 | 48 | impl Buf { 49 | /// Create empty buffer. It has no preallocated size. The underlying memory 50 | /// chunk is always deallocated when there are no useful bytes in the 51 | /// buffer. 52 | pub fn new() -> Buf { 53 | Buf { 54 | data: None, 55 | consumed: 0, 56 | remaining: 0, 57 | } 58 | } 59 | fn reserve(&mut self, bytes: usize) { 60 | self.data = self.data.take().map(|slice| { 61 | let old_cap = slice.len(); 62 | let old_bytes = old_cap - self.consumed() - self.remaining(); 63 | 64 | if self.consumed() > 0 { // let's allocate new slice and move 65 | let min_size = old_bytes + bytes; 66 | 67 | let mut vec = Vec::with_capacity(max(min_size, old_cap.saturating_mul(2))); 68 | let cap = vec.capacity(); 69 | unsafe { vec.set_len(cap) }; 70 | copy_memory(&slice[self.consumed()..old_cap - self.remaining()], 71 | &mut vec[..old_bytes]); 72 | self.remaining = cap - old_bytes; 73 | self.consumed = 0; 74 | Some(vec.into_boxed_slice()) 75 | } else { // just reallocate 76 | let mut vec = slice.into_vec(); 77 | vec.reserve(bytes); 78 | let cap = vec.capacity(); 79 | unsafe { vec.set_len(cap) }; 80 | self.remaining = cap - old_bytes; 81 | Some(vec.into_boxed_slice()) 82 | } 83 | }).unwrap_or_else(|| { 84 | let mut vec = Vec::with_capacity(max(bytes, ALLOC_MIN)); 85 | let cap = vec.capacity(); 86 | unsafe { vec.set_len(cap) }; 87 | 88 | self.remaining = cap; 89 | Some(vec.into_boxed_slice()) 90 | }) 91 | } 92 | fn reserve_exact(&mut self, bytes: usize) { 93 | self.data = self.data.take().map(|slice| { 94 | let old_cap = slice.len(); 95 | let old_bytes = old_cap - self.consumed() - self.remaining(); 96 | 97 | if self.consumed() > 0 { // let's allocate new slice and move 98 | let size = old_bytes + bytes; 99 | let mut vec = Vec::with_capacity(size); 100 | let cap = vec.capacity(); 101 | unsafe { vec.set_len(cap) }; 102 | copy_memory(&slice[self.consumed()..old_cap - self.remaining()], 103 | &mut vec[..old_bytes]); 104 | self.remaining = cap - old_bytes; 105 | self.consumed = 0; 106 | Some(vec.into_boxed_slice()) 107 | } else { // just reallocate 108 | let mut vec = slice.into_vec(); 109 | vec.reserve_exact(bytes); 110 | let cap = vec.capacity(); 111 | unsafe { vec.set_len(cap) }; 112 | self.remaining = cap - old_bytes; 113 | Some(vec.into_boxed_slice()) 114 | } 115 | }).unwrap_or_else(|| { 116 | let mut vec = Vec::with_capacity(bytes); 117 | let cap = vec.capacity(); 118 | unsafe { vec.set_len(cap) }; 119 | 120 | self.remaining = cap; 121 | Some(vec.into_boxed_slice()) 122 | }) 123 | } 124 | fn remaining(&self) -> usize { 125 | self.remaining as usize 126 | } 127 | fn consumed(&self) -> usize { 128 | self.consumed as usize 129 | } 130 | 131 | /// Mark the first `bytes` of the buffer as read. Basically it's shaving 132 | /// off bytes from the buffer, but does it efficiently. When there are 133 | /// no more bytes in the buffer it's deallocated. 134 | /// 135 | /// Note: Buffer currently doesn't shrink when calling this method. It's 136 | /// assumed that all bytes will be consumed shortly. In case you're 137 | /// appending to the buffer after consume, old data is discarded. 138 | /// 139 | /// # Panics 140 | /// 141 | /// Panics if `bytes` is larger than current length of buffer 142 | pub fn consume(&mut self, bytes: usize) { 143 | let ln = self.len(); 144 | assert!(bytes <= ln); 145 | if bytes == ln { 146 | *self = Buf::new(); 147 | } else { 148 | self.consumed += bytes; 149 | } 150 | } 151 | 152 | /// Allows removing an arbitrary range of bytes 153 | /// 154 | /// A more comprehensive version of `consume()`. It's occasionally useful 155 | /// if your data is in frames/chunks but you want to buffer the whole body 156 | /// anyway. E.g. in http chunked encoding you have each chunk prefixed by 157 | /// its length, but that doesn't mean you can't buffer the whole request 158 | /// into memory. This method allows you to continue reading the next chunk 159 | /// into the same buffer while removing the chunk length. 160 | /// 161 | /// Note: it's not super efficient, as it requires to move (copy) bytes 162 | /// after the range, in case range is neither at the start nor at the 163 | /// end of buffer. Still it should be faster than copying everything 164 | /// to yet another buffer. 165 | /// 166 | /// We never shrink the buffer here (except when it becomes empty, to 167 | /// keep this invariant), assuming that you will receive more data into 168 | /// the buffer shortly. 169 | /// 170 | /// The `RangeArgument` type is a temporary type until rust provides 171 | /// the one in standard library, you should use the range syntax directly: 172 | /// 173 | /// ```ignore 174 | /// buf.remove_range(5..7) 175 | /// ``` 176 | /// 177 | /// # Panics 178 | /// 179 | /// Panics if range is invalid for the buffer 180 | pub fn remove_range>(&mut self, range: R) { 181 | use range::RangeArgument::*; 182 | match range.into() { 183 | RangeTo(x) | Range(0, x) => self.consume(x), 184 | RangeFrom(0) => *self = Buf::new(), 185 | RangeFrom(x) => { 186 | let ln = self.len(); 187 | assert!(x <= ln); 188 | self.remaining += ln - x; 189 | } 190 | Range(x, y) => { 191 | let ln = self.len(); 192 | if x == y { return; } 193 | assert!(x < y); 194 | let removed_bytes = y - x; 195 | assert!(y <= ln); 196 | let start = self.consumed() + x; 197 | let end = self.consumed() + y; 198 | if let Some(ref mut data) = self.data { 199 | let dlen = data.len(); 200 | unsafe { 201 | copy(data[end..].as_ptr(), 202 | data[start..dlen - removed_bytes].as_mut_ptr(), 203 | dlen - end); 204 | } 205 | self.remaining += removed_bytes; 206 | } else { 207 | panic!("Not-existent buffere where data exists"); 208 | } 209 | } 210 | } 211 | } 212 | 213 | 214 | /// Capacity of the buffer. I.e. the bytes it is allocated for. Use for 215 | /// debugging or for calculating memory usage. Note it's not guaranteed 216 | /// that you can write `buf.capacity() - buf.len()` bytes without resize 217 | pub fn capacity(&self) -> usize { 218 | self.data.as_ref().map(|x| x.len()).unwrap_or(0) 219 | } 220 | 221 | /// Number of useful bytes in the buffer 222 | pub fn len(&self) -> usize { 223 | self.data.as_ref() 224 | .map(|x| x.len() - self.consumed() - self.remaining()) 225 | .unwrap_or(0) 226 | } 227 | 228 | /// If buffer is empty. Potentially a little bit faster than 229 | /// getting `len()` 230 | pub fn is_empty(&self) -> bool { 231 | self.data.is_none() 232 | } 233 | 234 | fn future_slice<'x>(&'x mut self) -> &'x mut [u8] { 235 | let rem = self.remaining(); 236 | self.data.as_mut() 237 | .map(|x| { 238 | let upto = x.len(); 239 | &mut x[upto - rem .. upto] 240 | }) 241 | .unwrap() 242 | } 243 | 244 | /// Extend buffer. Note unlike `Write::write()` and `read_from()` this 245 | /// method reserves as small as possible a chunk of memory. So it's 246 | /// inefficien to grow with this method. You may use the Write trait to 247 | /// grow incrementally. 248 | pub fn extend(&mut self, buf: &[u8]) { 249 | if buf.len() == 0 { return; } 250 | if self.remaining() < buf.len() { 251 | self.reserve_exact(buf.len()); 252 | } 253 | copy_memory(buf, &mut self.future_slice()[..buf.len()]); 254 | self.remaining -= buf.len(); 255 | } 256 | 257 | /// Read some bytes from stream (object implementing `Read`) into buffer 258 | /// 259 | /// Note this does *not* continue to read until getting `WouldBlock`. It 260 | /// passes all errors as is. It preallocates some chunk to read into 261 | /// buffer. It may be possible that the stream still has bytes buffered 262 | /// after this method returns. This method is expected either to be called 263 | /// until `WouldBlock` is returned or is used with level-triggered polling. 264 | pub fn read_from(&mut self, stream: &mut R) -> Result { 265 | if self.remaining() < READ_MIN { 266 | self.reserve(READ_MIN); 267 | } 268 | let bytes = match stream.read(self.future_slice()) { 269 | res @ Ok(0) | res @ Err(_) => { 270 | self.consume(0); 271 | return res; 272 | } 273 | Ok(x) => x, 274 | }; 275 | debug_assert!(bytes <= self.remaining()); 276 | self.remaining -= bytes; 277 | Ok(bytes) 278 | } 279 | 280 | /// Reads no more than max bytes into buffer and returns boolean flag 281 | /// of whether max bytes are reached 282 | /// 283 | /// Except for the limit on number of bytes and slightly different 284 | /// allocation strategy, this method has the same considerations as 285 | /// read_from 286 | /// 287 | /// Note this method might be used for two purposes: 288 | /// 289 | /// 1. Limit number of bytes buffered until parser can process data 290 | /// (for example HTTP header size, which is number of bytes read before 291 | /// `\r\n\r\n` delimiter reached) 292 | /// 2. Wait until exact number of bytes are fully received 293 | /// 294 | /// Since we support (1) we don't preallocate buffer for exact size of 295 | /// the `max` value. It also helps a little in case (2) for minimizing 296 | /// DDoS attack vector. If that doesn't suit you, you may wish to use 297 | /// `Vec::with_capacity()` for the purpose of (2). 298 | /// 299 | /// On the contrary we don't overallocate more than `max` bytes, so if 300 | /// you expect data to go after exact number of bytes read, it might be 301 | /// better to use `read_from()` and check buffer length. 302 | /// 303 | pub fn read_max_from(&mut self, max: usize, stream: &mut R) 304 | -> Result 305 | { 306 | let todo = max.saturating_sub(self.len()); 307 | if todo == 0 { 308 | return Ok(true); 309 | } 310 | if self.remaining() < READ_MIN { 311 | if self.capacity().saturating_mul(2) < max { 312 | // TODO is too large we may never need so big buffer 313 | self.reserve(READ_MIN); 314 | } else { 315 | self.reserve_exact(todo); 316 | } 317 | } 318 | let res = { 319 | let slc = self.future_slice(); 320 | let do_now = min(slc.len(), todo); 321 | stream.read(&mut slc[..do_now]) 322 | }; 323 | let bytes = match res { 324 | Ok(0) => { 325 | self.consume(0); 326 | return Ok(false); 327 | } 328 | Err(e) => { 329 | self.consume(0); 330 | return Err(e); 331 | } 332 | Ok(x) => x, 333 | }; 334 | debug_assert!(bytes <= self.remaining()); 335 | self.remaining -= bytes; 336 | Ok(self.len() >= max) 337 | } 338 | 339 | /// Write contents of buffer to the stream (object implementing 340 | /// the Write trait). We assume that stream is non-blocking, use 341 | /// `Write::write` (instead of `Write::write_all`) and return all errors 342 | /// to the caller (including `WouldBlock` or `Interrupted`). 343 | /// 344 | /// In addition to returning the number of bytes written, it also 345 | /// `consume()`s those bytes from the buffer, so it's safe to retry calling 346 | /// the method at any moment. Also it's a common pattern to append more 347 | /// data to the buffer between calls. 348 | pub fn write_to(&mut self, sock: &mut W) -> Result { 349 | let bytes = match sock.write(&self[..]) { 350 | Ok(bytes) => bytes, 351 | Err(e) => return Err(e), 352 | }; 353 | self.consume(bytes); 354 | Ok(bytes) 355 | } 356 | 357 | /// Splits buffer into two at the given index. 358 | /// 359 | /// `self` contains bytes `[0, at)` and the returned `Buf` contains 360 | /// bytes `[at, len)`. 361 | /// 362 | /// Reallocates smaller part of buffer. 363 | /// 364 | /// # Panics 365 | /// 366 | /// Panics if at > len. 367 | /// 368 | /// # Examples 369 | /// ```rust 370 | /// let mut buf = netbuf::Buf::new(); 371 | /// buf.extend(b"Hello World!"); 372 | /// let tail = buf.split_off(6); 373 | /// assert_eq!(&buf[..], b"Hello "); 374 | /// assert_eq!(&tail[..], b"World!"); 375 | /// ``` 376 | pub fn split_off(&mut self, at: usize) -> Buf { 377 | assert!(at <= self.len()); 378 | let mut tail = Buf::new(); 379 | match self.data.as_ref().map(|x| x.len() - at > at) { 380 | Some(true) => { // re-allocate self; 381 | swap(&mut tail, self); 382 | if at > 0 { 383 | self.extend(&tail[..at]); 384 | tail.consume(at); 385 | } 386 | }, 387 | Some(false) => { // allocate for tail; 388 | tail.extend(&self[at..]); 389 | self.remove_range(at..); 390 | }, 391 | None => {} 392 | } 393 | tail 394 | } 395 | 396 | /// Returns the byte at the index, or `None` if the index is 397 | /// out of bounds. 398 | pub fn get(&self, index: usize) -> Option { 399 | if index >= self.len() { 400 | return None; 401 | } 402 | let consumed = self.consumed(); 403 | if let Some(ref data) = self.data { 404 | Some(data[consumed + index]) 405 | } else { 406 | None 407 | } 408 | } 409 | 410 | /// Returns a mutable reference to the byte at the index, or 411 | /// `None` if the index is out of bounds. 412 | pub fn get_mut(&mut self, index: usize) -> Option<&mut u8> { 413 | if index >= self.len() { 414 | return None; 415 | } 416 | let consumed = self.consumed(); 417 | if let Some(ref mut data) = self.data { 418 | Some(&mut data[consumed + index]) 419 | } else { 420 | None 421 | } 422 | } 423 | 424 | } 425 | 426 | 427 | impl Debug for Buf { 428 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 429 | write!(f, "Buf {{ len={}; consumed={}; remaining={} }}", 430 | self.len(), self.consumed(), self.remaining()) 431 | } 432 | } 433 | 434 | impl AsRef<[u8]> for Buf { 435 | fn as_ref(&self) -> &[u8] { 436 | &self[..] 437 | } 438 | } 439 | 440 | impl Into> for Buf { 441 | fn into(mut self) -> Vec { 442 | if self.consumed == 0 { 443 | self.data.take().map(|slice| { 444 | let mut vec = slice.into_vec(); 445 | if self.remaining > 0 { 446 | let nlen = vec.len() - self.remaining(); 447 | unsafe { vec.set_len(nlen) }; 448 | } 449 | vec 450 | }).unwrap_or_else(Vec::new) 451 | } else { 452 | self[..].to_vec() 453 | } 454 | } 455 | } 456 | 457 | impl Index for Buf { 458 | type Output = u8; 459 | fn index<'x>(&'x self, index: usize) -> &'x u8 { 460 | if let Some(ref data) = self.data { 461 | return &data[self.consumed() + index] 462 | } 463 | panic!("cannot index empty buffer"); 464 | 465 | } 466 | } 467 | 468 | impl Index for Buf { 469 | type Output = [u8]; 470 | fn index<'x>(&'x self, _idx: RangeFull) -> &'x[u8] { 471 | self.data.as_ref() 472 | .map(|x| &x[self.consumed()..x.len() - self.remaining()]) 473 | .unwrap_or(b"") 474 | } 475 | } 476 | 477 | impl Index> for Buf { 478 | type Output = [u8]; 479 | fn index<'x>(&'x self, slice: RangeTo) -> &'x[u8] { 480 | let idx = slice.end; 481 | if idx == 0 { 482 | return b""; 483 | } 484 | assert!(idx <= self.len()); 485 | &self.data.as_ref().unwrap()[self.consumed()..self.consumed() + idx] 486 | } 487 | } 488 | 489 | impl Index> for Buf { 490 | type Output = [u8]; 491 | fn index<'x>(&'x self, slice: RangeFrom) -> &'x[u8] { 492 | let idx = slice.start; 493 | if idx == self.len() { 494 | return b""; 495 | } 496 | assert!(idx <= self.len()); 497 | let buf = &self.data.as_ref().unwrap(); 498 | &buf[self.consumed() + idx .. buf.len() - self.remaining()] 499 | } 500 | } 501 | 502 | impl Index> for Buf { 503 | type Output = [u8]; 504 | fn index<'x>(&'x self, slice: Range) -> &'x[u8] { 505 | let start = slice.start; 506 | let end = slice.end; 507 | if end == 0 { 508 | return b""; 509 | } 510 | assert!(end <= self.len()); 511 | assert!(start <= end); 512 | let buf = &self.data.as_ref().unwrap(); 513 | &buf[self.consumed() + start .. self.consumed() + end] 514 | } 515 | } 516 | 517 | impl IndexMut for Buf { 518 | fn index_mut<'x>(&'x mut self, index: usize) -> &'x mut u8 { 519 | let consumed = self.consumed(); 520 | if let Some(ref mut data) = self.data { 521 | return &mut data[consumed + index] 522 | } 523 | panic!("cannot index empty buffer"); 524 | } 525 | } 526 | 527 | impl IndexMut for Buf { 528 | fn index_mut<'x>(&'x mut self, _idx: RangeFull) -> &'x mut[u8] { 529 | let consumed = self.consumed(); 530 | let remaining = self.remaining(); 531 | self.data.as_mut() 532 | .map(|x| { 533 | let len = x.len(); 534 | &mut x[consumed..len - remaining] 535 | }) 536 | .unwrap_or(&mut []) 537 | } 538 | } 539 | 540 | impl IndexMut> for Buf { 541 | fn index_mut<'x>(&'x mut self, slice: RangeTo) -> &'x mut[u8] { 542 | let idx = slice.end; 543 | if idx == 0 { 544 | return &mut []; 545 | } 546 | assert!(idx <= self.len()); 547 | let consumed = self.consumed(); 548 | &mut self.data.as_mut().unwrap()[consumed..consumed + idx] 549 | } 550 | } 551 | 552 | impl IndexMut> for Buf { 553 | fn index_mut<'x>(&'x mut self, slice: RangeFrom) -> &'x mut[u8] { 554 | let idx = slice.start; 555 | if idx == self.len() { 556 | return &mut []; 557 | } 558 | assert!(idx <= self.len()); 559 | let consumed = self.consumed(); 560 | let remaining = self.remaining(); 561 | let buf = self.data.as_mut().unwrap(); 562 | let len = buf.len(); 563 | &mut buf[consumed + idx .. len - remaining] 564 | } 565 | } 566 | 567 | impl IndexMut> for Buf { 568 | fn index_mut<'x>(&'x mut self, slice: Range) -> &'x mut[u8] { 569 | let start = slice.start; 570 | let end = slice.end; 571 | if end == 0 { 572 | return &mut []; 573 | } 574 | assert!(end <= self.len()); 575 | assert!(start <= end); 576 | let consumed = self.consumed(); 577 | let buf = self.data.as_mut().unwrap(); 578 | &mut buf[consumed + start .. consumed + end] 579 | } 580 | } 581 | 582 | impl Write for Buf { 583 | fn write(&mut self, buf: &[u8]) -> Result { 584 | if buf.len() == 0 { 585 | return Ok(0); 586 | } 587 | if self.remaining() < buf.len() { 588 | self.reserve(buf.len()); 589 | } 590 | copy_memory(buf, &mut self.future_slice()[..buf.len()]); 591 | self.remaining -= buf.len(); 592 | Ok(buf.len()) 593 | } 594 | fn flush(&mut self) -> Result<()> { Ok(()) } 595 | } 596 | 597 | impl Default for Buf { 598 | fn default() -> Self { 599 | Buf::new() 600 | } 601 | } 602 | 603 | #[cfg(test)] 604 | mod test { 605 | use std::mem::size_of; 606 | use std::io::{self, Read, Write}; 607 | use super::Buf; 608 | use super::ALLOC_MIN; 609 | use mockstream::SharedMockStream; 610 | 611 | struct ReadErr; 612 | 613 | impl Read for ReadErr { 614 | fn read(&mut self, _: &mut [u8]) -> Result { 615 | Err(io::Error::new(io::ErrorKind::WouldBlock, "fake would block")) 616 | } 617 | } 618 | 619 | #[test] 620 | #[cfg(target_arch="x86_64")] 621 | fn size32() { 622 | assert_eq!(size_of::(), 32); 623 | } 624 | 625 | #[test] 626 | #[cfg(target_arch="x86")] 627 | fn size32() { 628 | assert_eq!(size_of::(), 16); 629 | } 630 | 631 | #[test] 632 | fn empty() { 633 | let buf = Buf::new(); 634 | assert_eq!(&buf[..], b""); 635 | assert_eq!(format!("{:?}", buf), "Buf { len=0; consumed=0; remaining=0 }") 636 | } 637 | 638 | #[test] 639 | fn read_from_empty() { 640 | let mut s = SharedMockStream::new(); 641 | let mut buf = Buf::new(); 642 | assert_eq!(buf.read_from(&mut s).unwrap(), 0); 643 | assert!(buf.is_empty()); 644 | assert_eq!(&buf[..], b""); 645 | assert_eq!(format!("{:?}", buf), "Buf { len=0; consumed=0; remaining=0 }") 646 | } 647 | 648 | #[test] 649 | fn read_from_err() { 650 | let mut buf = Buf::new(); 651 | buf.read_from(&mut ReadErr).unwrap_err(); 652 | assert!(buf.is_empty()); 653 | assert_eq!(&buf[..], b""); 654 | assert_eq!(format!("{:?}", buf), "Buf { len=0; consumed=0; remaining=0 }") 655 | } 656 | 657 | #[test] 658 | fn read_max_from_empty() { 659 | let mut s = SharedMockStream::new(); 660 | let mut buf = Buf::new(); 661 | assert_eq!(buf.read_max_from(1024, &mut s).unwrap(), false); 662 | assert!(buf.is_empty()); 663 | assert_eq!(&buf[..], b""); 664 | assert_eq!(format!("{:?}", buf), "Buf { len=0; consumed=0; remaining=0 }") 665 | } 666 | 667 | #[test] 668 | fn read_max_from_err() { 669 | let mut buf = Buf::new(); 670 | buf.read_max_from(1024, &mut ReadErr).unwrap_err(); 671 | assert!(buf.is_empty()); 672 | assert_eq!(&buf[..], b""); 673 | assert_eq!(format!("{:?}", buf), "Buf { len=0; consumed=0; remaining=0 }") 674 | } 675 | 676 | #[test] 677 | fn read_from() { 678 | let mut s = SharedMockStream::new(); 679 | s.push_bytes_to_read(b"hello"); 680 | let mut buf = Buf::new(); 681 | assert_eq!(buf.read_from(&mut s).unwrap(), 5); 682 | assert_eq!(&buf[..], b"hello"); 683 | } 684 | 685 | #[test] 686 | fn read_max_from() { 687 | let mut s = SharedMockStream::new(); 688 | s.push_bytes_to_read(b"hello"); 689 | let mut buf = Buf::new(); 690 | s.push_bytes_to_read(b"hello world"); 691 | assert!(!buf.read_max_from(1024*1024, &mut s).unwrap()); 692 | assert_eq!(&buf[..], b"hellohello world"); 693 | assert!(buf.capacity() < ALLOC_MIN*2); 694 | s.push_bytes_to_read(b" from me!Oh, crap!"); 695 | assert!(buf.read_max_from(25, &mut s).unwrap()); 696 | assert_eq!(&buf[..], b"hellohello world from me!"); 697 | assert!(buf.capacity() < ALLOC_MIN*2); 698 | assert!(buf.read_max_from(25, &mut s).unwrap()); 699 | assert_eq!(&buf[..], b"hellohello world from me!"); 700 | assert!(buf.capacity() < ALLOC_MIN*2); 701 | buf.consume(5); 702 | assert!(buf.read_max_from(22, &mut s).unwrap()); 703 | assert_eq!(&buf[..], b"hello world from me!Oh"); 704 | assert!(buf.capacity() < ALLOC_MIN*2); 705 | } 706 | 707 | #[test] 708 | fn two_reads() { 709 | let mut s = SharedMockStream::new(); 710 | s.push_bytes_to_read(b"hello"); 711 | let mut buf = Buf::new(); 712 | buf.read_from(&mut s).unwrap(); 713 | s.push_bytes_to_read(b" world"); 714 | buf.read_from(&mut s).unwrap(); 715 | assert_eq!(&buf[..], b"hello world"); 716 | assert_eq!(buf.capacity(), ALLOC_MIN); 717 | } 718 | 719 | #[test] 720 | fn realloc() { 721 | let mut s = SharedMockStream::new(); 722 | s.push_bytes_to_read(b"hello"); 723 | let mut buf = Buf::new(); 724 | buf.read_from(&mut s).unwrap(); 725 | s.push_bytes_to_read(&b"abcdefg".iter().cloned().cycle().take(1024*1024) 726 | .collect::>()[..]); 727 | buf.read_from(&mut s).unwrap(); 728 | assert_eq!(&buf[..9], b"helloabcd"); 729 | assert_eq!(buf.len(), ALLOC_MIN); 730 | assert_eq!(buf.capacity(), ALLOC_MIN); 731 | buf.read_from(&mut s).unwrap(); 732 | assert_eq!(buf.len(), buf.capacity()); 733 | assert!(buf.capacity() >= 32768); 734 | println!("Capacity {}", buf.capacity()); 735 | buf.read_from(&mut s).unwrap(); 736 | println!("Capacity {}", buf.capacity()); 737 | buf.read_from(&mut s).unwrap(); 738 | println!("Capacity {}", buf.capacity()); 739 | buf.read_from(&mut s).unwrap(); 740 | println!("Capacity {}", buf.capacity()); 741 | buf.read_from(&mut s).unwrap(); 742 | println!("Capacity {}", buf.capacity()); 743 | buf.read_from(&mut s).unwrap(); 744 | println!("Capacity {}", buf.capacity()); 745 | buf.read_from(&mut s).unwrap(); 746 | println!("Capacity {}", buf.capacity()); 747 | assert_eq!(buf.len(), 1048576 + 5); 748 | assert!(buf.capacity() >= buf.len()); 749 | assert!(buf.capacity() <= 2100000); 750 | assert_eq!(&buf[buf.len()-10..], b"bcdefgabcd"); 751 | } 752 | 753 | #[test] 754 | fn two_writes() { 755 | let mut buf = Buf::new(); 756 | assert_eq!(buf.write(b"hello").unwrap(), 5); 757 | assert_eq!(buf.write(b" world").unwrap(), 6); 758 | assert_eq!(&buf[..], b"hello world"); 759 | assert_eq!(buf.capacity(), ALLOC_MIN); 760 | } 761 | 762 | #[test] 763 | fn two_extends() { 764 | let mut buf = Buf::new(); 765 | buf.extend(b"hello"); 766 | buf.extend(b" world"); 767 | assert_eq!(&buf[..], b"hello world"); 768 | assert_eq!(buf.capacity(), 11); 769 | } 770 | 771 | #[test] 772 | fn write_extend() { 773 | let mut buf = Buf::new(); 774 | buf.write(b"hello").unwrap(); 775 | buf.extend(b" world"); 776 | assert_eq!(&buf[..], b"hello world"); 777 | assert_eq!(buf.capacity(), ALLOC_MIN); 778 | } 779 | 780 | #[test] 781 | fn extend_write() { 782 | let mut buf = Buf::new(); 783 | buf.extend(b"hello"); 784 | buf.write(b" world").unwrap(); 785 | assert_eq!(&buf[..], b"hello world"); 786 | let cap = buf.capacity(); 787 | // We don't know exact allocation policy for vec 788 | // So this check is fuzzy 789 | assert!(cap >= 11); 790 | assert!(cap < 256); 791 | } 792 | 793 | #[test] 794 | fn extend_empty() { 795 | let mut buf = Buf::new(); 796 | buf.extend(b""); 797 | assert_eq!(&buf[..], b""); 798 | assert_eq!(buf.len(), 0); 799 | assert_eq!(buf.capacity(), 0); 800 | } 801 | 802 | #[test] 803 | fn into() { 804 | let mut buf = Buf::new(); 805 | buf.extend(b"hello"); 806 | buf.write(b" world").unwrap(); 807 | let vec: Vec = buf.into(); 808 | assert_eq!(&vec[..], b"hello world"); 809 | let cap = vec.capacity(); 810 | // We don't know exact allocation policy for vec 811 | // So this check is fuzzy 812 | assert!(cap >= 11); 813 | assert!(cap < 256); 814 | } 815 | 816 | #[test] 817 | fn consumed_into() { 818 | let mut buf = Buf::new(); 819 | buf.extend(b"hello"); 820 | buf.write(b" world").unwrap(); 821 | buf.consume(6); 822 | let vec: Vec = buf.into(); 823 | assert_eq!(&vec[..], b"world"); 824 | assert_eq!(vec.capacity(), 5); 825 | } 826 | #[test] 827 | fn write_to() { 828 | let mut s = SharedMockStream::new(); 829 | let mut buf = Buf::new(); 830 | buf.extend(b"hello world"); 831 | assert_eq!(buf.write_to(&mut s).unwrap(), 11); 832 | assert_eq!(&s.pop_bytes_written()[..], b"hello world"); 833 | } 834 | 835 | #[test] 836 | fn empty_write_to_empty() { 837 | let mut buf = Buf::new(); 838 | let mut empty = Buf::new(); 839 | assert_eq!(empty.write_to(&mut buf).unwrap(), 0); 840 | } 841 | 842 | #[test] 843 | fn extend_consume_extend() { 844 | let mut buf = Buf::new(); 845 | buf.extend(b"hello"); 846 | buf.consume(3); 847 | buf.extend(b" world"); 848 | assert_eq!(&buf[..], b"lo world"); 849 | assert_eq!(buf.capacity(), 8); 850 | } 851 | 852 | #[test] 853 | fn extend_consume_write() { 854 | let mut buf = Buf::new(); 855 | buf.extend(b"hello"); 856 | buf.consume(3); 857 | buf.write(b"Some larger string for you").unwrap(); 858 | assert_eq!(&buf[..], b"loSome larger string for you"); 859 | assert_eq!(buf.capacity(), 28); 860 | } 861 | 862 | #[test] 863 | fn consume_all() { 864 | let mut buf = Buf::new(); 865 | buf.extend(b"hello"); 866 | buf.write(b" world").unwrap(); 867 | buf.consume(11); 868 | assert_eq!(buf.capacity(), 0); 869 | assert_eq!(&buf[..], b""); 870 | let vec: Vec = buf.into(); 871 | assert_eq!(&vec[..], b""); 872 | assert_eq!(vec.capacity(), 0); 873 | } 874 | 875 | #[test] 876 | fn index() { 877 | let mut buf = Buf::new(); 878 | buf.extend(b"Hello World!"); 879 | assert_eq!(buf[0], b'H'); 880 | assert_eq!(buf[6], b'W'); 881 | buf.consume(2); 882 | assert_eq!(buf[2], b'o'); 883 | assert_eq!(buf[8], b'd'); 884 | } 885 | 886 | #[test] 887 | fn index_mut() { 888 | let mut buf = Buf::new(); 889 | buf.extend(b"Hello World!"); 890 | assert_eq!(buf[0], b'H'); 891 | buf[0] = b'h'; 892 | assert_eq!(buf[6], b'W'); 893 | buf[6] = b'M'; 894 | assert_eq!(&buf[..], b"hello Morld!"); 895 | buf.consume(2); 896 | buf[1] = b'e'; 897 | buf[5] = b'e'; 898 | buf[8] = b'e'; 899 | assert_eq!(&buf[..], b"leo Merle!"); 900 | } 901 | 902 | #[test] 903 | fn get() { 904 | let mut buf = Buf::new(); 905 | assert_eq!(buf.get(0), None); 906 | buf.extend(b"Hello World!"); 907 | assert_eq!(buf.get(0), Some(b'H')); 908 | assert_eq!(buf.get(6), Some(b'W')); 909 | assert_eq!(buf.get(11), Some(b'!')); 910 | assert_eq!(buf.get(12), None); 911 | buf.consume(2); 912 | assert_eq!(buf.get(2), Some(b'o')); 913 | assert_eq!(buf.get(8), Some(b'd')); 914 | assert_eq!(buf.get(9), Some(b'!')); 915 | assert_eq!(buf.get(10), None); 916 | } 917 | 918 | #[test] 919 | fn get_mut() { 920 | let mut buf = Buf::new(); 921 | assert_eq!(buf.get_mut(0), None); 922 | buf.extend(b"Hello World!"); 923 | assert_eq!(buf.get_mut(0), Some(&mut b'H')); 924 | if let Some(x) = buf.get_mut(0) { *x = b'h'; } 925 | assert_eq!(buf.get_mut(6), Some(&mut b'W')); 926 | if let Some(x) = buf.get_mut(6) { *x = b'M'; } 927 | assert_eq!(&buf[..], b"hello Morld!"); 928 | assert_eq!(buf.get_mut(11), Some(&mut b'!')); 929 | assert_eq!(buf.get_mut(12), None); 930 | buf.consume(2); 931 | if let Some(x) = buf.get_mut(1) { *x = b'e'; } 932 | if let Some(x) = buf.get_mut(5) { *x = b'e'; } 933 | if let Some(x) = buf.get_mut(8) { *x = b'e'; } 934 | assert_eq!(&buf[..], b"leo Merle!"); 935 | assert_eq!(buf.get_mut(9), Some(&mut b'!')); 936 | assert_eq!(buf.get_mut(10), None); 937 | } 938 | 939 | #[test] 940 | fn ranges() { 941 | let mut buf = Buf::new(); 942 | buf.extend(b"Hello world!"); 943 | assert_eq!(&buf[..], b"Hello world!"); 944 | assert_eq!(&buf[..0], b""); 945 | assert_eq!(&buf[..5], b"Hello"); 946 | assert_eq!(&buf[..12], b"Hello world!"); 947 | assert_eq!(&buf[..7], b"Hello w"); 948 | assert_eq!(&buf[0..], b"Hello world!"); 949 | assert_eq!(&buf[3..], b"lo world!"); 950 | assert_eq!(&buf[6..], b"world!"); 951 | assert_eq!(&buf[12..], b""); 952 | assert_eq!(&buf[0..0], b""); 953 | assert_eq!(&buf[2..8], b"llo wo"); 954 | assert_eq!(&buf[0..12], b"Hello world!"); 955 | assert_eq!(&buf[0..5], b"Hello"); 956 | assert_eq!(&buf[7..12], b"orld!"); 957 | assert_eq!(&buf[3..3], b""); 958 | assert_eq!(&buf[3..9], b"lo wor"); 959 | } 960 | 961 | #[test] 962 | fn consume_ranges() { 963 | let mut buf = Buf::new(); 964 | buf.extend(b"Crappy stuff"); 965 | buf.extend(b"Hello world!"); 966 | buf.consume(12); 967 | assert_eq!(&buf[..], b"Hello world!"); 968 | assert_eq!(&buf[..0], b""); 969 | assert_eq!(&buf[..5], b"Hello"); 970 | assert_eq!(&buf[..12], b"Hello world!"); 971 | assert_eq!(&buf[..7], b"Hello w"); 972 | assert_eq!(&buf[0..], b"Hello world!"); 973 | assert_eq!(&buf[3..], b"lo world!"); 974 | assert_eq!(&buf[6..], b"world!"); 975 | assert_eq!(&buf[12..], b""); 976 | assert_eq!(&buf[2..8], b"llo wo"); 977 | assert_eq!(&buf[0..12], b"Hello world!"); 978 | assert_eq!(&buf[0..5], b"Hello"); 979 | assert_eq!(&buf[7..12], b"orld!"); 980 | assert_eq!(&buf[3..3], b""); 981 | assert_eq!(&buf[3..9], b"lo wor"); 982 | } 983 | 984 | #[test] 985 | fn remove_ranges() { 986 | let mut buf = Buf::new(); 987 | buf.extend(b"Crappy stuff"); 988 | buf.extend(b"Hello world!"); 989 | assert_eq!(&buf[..], b"Crappy stuffHello world!"); 990 | buf.remove_range(..4); 991 | assert_eq!(&buf[..], b"py stuffHello world!"); 992 | buf.remove_range(3..8); 993 | assert_eq!(&buf[..], b"py Hello world!"); 994 | buf.remove_range(7..14); 995 | assert_eq!(&buf[..], b"py Hell!"); 996 | buf.remove_range(7..); 997 | assert_eq!(&buf[..], b"py Hell"); 998 | let end = buf.len(); 999 | buf.remove_range(2..end); 1000 | assert_eq!(&buf[..], b"py"); 1001 | } 1002 | 1003 | #[test] 1004 | fn mut_ranges() { 1005 | let mut buf = Buf::new(); 1006 | buf.extend(b"Crappy stuff"); 1007 | buf.extend(b"Hello world!"); 1008 | buf.consume(12); 1009 | buf[..].clone_from_slice(b"HELLO WORLD."); 1010 | assert_eq!(&buf[..], b"HELLO WORLD."); 1011 | buf[..5].clone_from_slice(b"hell!"); 1012 | assert_eq!(&buf[..], b"hell! WORLD."); 1013 | buf[4..10].clone_from_slice(b"o worl"); 1014 | assert_eq!(&buf[..], b"hello worlD."); 1015 | buf[10..].clone_from_slice(b"d!"); 1016 | assert_eq!(&buf[..], b"hello world!"); 1017 | } 1018 | 1019 | #[test] 1020 | fn split_off_realloc_self() { 1021 | let mut buf = Buf::new(); 1022 | buf.reserve_exact(20); 1023 | buf.extend(b"Hello World"); 1024 | let tail = buf.split_off(5); 1025 | assert_eq!(&buf[..], b"Hello"); 1026 | assert_eq!(buf.consumed(), 0); 1027 | assert_eq!(buf.len(), 5); 1028 | 1029 | assert_eq!(&tail[..], b" World"); 1030 | assert_eq!(tail.consumed(), 5); 1031 | assert_eq!(tail.len(), 6); 1032 | } 1033 | 1034 | #[test] 1035 | fn split_off_alloc_tail() { 1036 | let mut buf = Buf::new(); 1037 | buf.reserve_exact(20); 1038 | buf.extend(b"Hello World!..."); 1039 | assert_eq!(buf.capacity(), 20); 1040 | 1041 | let tail = buf.split_off(11); 1042 | assert_eq!(&buf[..], b"Hello World"); 1043 | assert_eq!(buf.capacity(), 20); 1044 | assert_eq!(buf.consumed(), 0); 1045 | assert_eq!(buf.len(), 11); 1046 | 1047 | assert_eq!(&tail[..], b"!..."); 1048 | assert_eq!(tail.capacity(), 4); 1049 | assert_eq!(tail.consumed(), 0); 1050 | assert_eq!(tail.len(), 4); 1051 | 1052 | let mut buf = Buf::new(); 1053 | buf.extend(b"abcdefg"); 1054 | let tail = buf.split_off(0); 1055 | assert_eq!(&tail[..], b"abcdefg"); 1056 | assert_eq!(&buf[..], b""); 1057 | } 1058 | } 1059 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! # Netbuf 2 | //! 3 | //! [Documentation](https://docs.rs/netbuf) | 4 | //! [Github](https://github.com/tailhook/netbuf) | 5 | //! [Crate](https://crates.io/crates/netbuf) 6 | //! 7 | //! This module currently includes single `Buf` struct for holding buffers. 8 | //! Comparing to `Vec` class buffer has different allocation policy and has 9 | //! a marker of consumed data (i.e. already processed by protocol parser or 10 | //! already written to socket) 11 | //! 12 | //! The `Buf` is deemed good both for input and output network buffer. 13 | //! 14 | //! It also contains helper methods `read_from` and `write_to` which are used 15 | //! to read and append bytes from stream that implements Read and write bytes 16 | //! from buffer to a stream which implements Write respectively. 17 | //! 18 | //! Note there are basically three ways to fill the buffer: 19 | //! 20 | //! * `Buf::read_from` -- preallocates some chunk and gives it to object 21 | //! implemeting Read 22 | //! * `Write::write` -- writes chunk to buffer assuming more data will follow 23 | //! shortly, i.e. it does large preallocations 24 | //! * `Buf::extend` -- writes chunk to buffer assuming it will not grow in the 25 | //! near perspective, so it allocates minimum chunk to hold the data 26 | //! 27 | //! In other words you should use: 28 | //! 29 | //! * `Buf::read_from` -- to read from the network 30 | //! * `Write::write` -- when you are constructing object directly to the buffer 31 | //! incrementally 32 | //! * `Buf::extend` -- when you put whole object in place and give it to the 33 | //! network code for sending 34 | //! 35 | //! More documentation is found in `Buf` object itself 36 | 37 | #[cfg(test)] extern crate mockstream; 38 | 39 | mod buf; 40 | mod range; 41 | 42 | pub use buf::Buf; 43 | pub use range::RangeArgument; 44 | -------------------------------------------------------------------------------- /src/range.rs: -------------------------------------------------------------------------------- 1 | use std::ops::{Range, RangeFrom, RangeTo, RangeFull}; 2 | 3 | /// Temporary type until the one in stdlib is made stable 4 | pub enum RangeArgument { 5 | RangeFrom(usize), 6 | Range(usize, usize), 7 | RangeTo(usize), 8 | } 9 | 10 | impl From> for RangeArgument { 11 | fn from(r: Range) -> RangeArgument { 12 | RangeArgument::Range(r.start, r.end) 13 | } 14 | } 15 | impl From> for RangeArgument { 16 | fn from(r: RangeFrom) -> RangeArgument { 17 | RangeArgument::RangeFrom(r.start) 18 | } 19 | } 20 | impl From> for RangeArgument { 21 | fn from(r: RangeTo) -> RangeArgument { 22 | RangeArgument::RangeTo(r.end) 23 | } 24 | } 25 | impl From for RangeArgument { 26 | fn from(_: RangeFull) -> RangeArgument { 27 | RangeArgument::RangeFrom(0) 28 | } 29 | } 30 | 31 | -------------------------------------------------------------------------------- /vagga.yaml: -------------------------------------------------------------------------------- 1 | commands: 2 | 3 | make: !Command 4 | description: Build netbuf library 5 | container: ubuntu 6 | run: [cargo, build] 7 | 8 | test: !Command 9 | description: Test netbuf library 10 | container: ubuntu 11 | environ: 12 | RUST_BACKTRACE: 1 13 | run: [cargo, test] 14 | 15 | coverage: !Command 16 | description: Run coverage tests for netbuf library 17 | container: ubuntu 18 | environ: 19 | RUST_BACKTRACE: 1 20 | run: | 21 | cargo test --no-run 22 | rm -rf target/cov 23 | kcov target/cov target/debug/netbuf-638268726e961e5a 24 | 25 | _bulk: !Command 26 | description: Run `bulk` command (for version bookkeeping) 27 | container: ubuntu 28 | run: [bulk] 29 | 30 | cargo: !Command 31 | description: Run any cargo command 32 | container: ubuntu 33 | run: [cargo] 34 | 35 | docs: !Command 36 | description: Generate documentation 37 | container: ubuntu 38 | run: [cargo, doc] 39 | 40 | containers: 41 | 42 | ubuntu: 43 | setup: 44 | - !Ubuntu xenial 45 | - !UbuntuUniverse 46 | - !Install [make, wget, ca-certificates, vim, 47 | libssl-dev, build-essential] 48 | 49 | - !TarInstall 50 | url: "https://static.rust-lang.org/dist/rust-1.25.0-x86_64-unknown-linux-gnu.tar.gz" 51 | script: "./install.sh --prefix=/usr \ 52 | --components=rustc,rust-std-x86_64-unknown-linux-gnu,cargo" 53 | 54 | - !BuildDeps [libcurl4-openssl-dev, libelf-dev, libdw-dev, cmake, 55 | python, pkg-config] 56 | - !Install [libdw1, libelf1, libcurl3] 57 | - &bulk !Tar 58 | url: "https://github.com/tailhook/bulk/releases/download/v0.4.11/bulk-v0.4.11.tar.gz" 59 | sha256: b718bb8448e726690c94d98d004bf7575f7a429106ec26ad3faf11e0fd9a7978 60 | path: / 61 | - !GitInstall 62 | url: git://github.com/SimonKagstrom/kcov 63 | script: | 64 | cmake . 65 | make 66 | make install 67 | 68 | environ: 69 | HOME: /work/target 70 | 71 | nightly: 72 | setup: 73 | - !Ubuntu xenial 74 | - !UbuntuUniverse 75 | - !Install [make, wget, ca-certificates, 76 | libssl-dev, build-essential] 77 | 78 | - !TarInstall 79 | url: "http://static.rust-lang.org/dist/rust-nightly-x86_64-unknown-linux-gnu.tar.gz" 80 | script: "./install.sh --prefix=/usr --components=rustc,cargo" 81 | 82 | environ: 83 | HOME: /work/target 84 | 85 | --------------------------------------------------------------------------------