从具有不同长度的向量中获取可变切片?

时间:2015-08-23 22:29:56

标签: rust

我试图将矢量用作缓冲区like this,我想知道是否有办法从矢量中取出切片而没有growing it,所以代码喜欢这项工作:

fn example(r: Read) {
    let buffer: Vec<u8> = Vec::with_capacity(1024);
    let slice: &mut[u8] = &mut buffer;
    r.read(slice); // doesnt work since the slice has length zero
}

2 个答案:

答案 0 :(得分:5)

如果只是为了获得一小部分容量,那么您将获得一些未初始化的数据。这是不安全的。

可以使用Vec&#39; set_len执行此操作。然而

这样做的基本方法是

unsafe {
    buffer.set_len(buffer.capacity());
    let new_len = try!(r.read(slice));
    buffer.set_len(cmp::min(buffer.len(), new_len));
}

如果您不完全信任cmp::min的实施,则需要read,因为不正确的输出会导致设置的时间过长。

答案 1 :(得分:0)

我想在@Veedrac回答中添加三个细节。

1 - 这是从{% load service_path_extras %} {% load staticfiles %} <div class = "well well-light"> <div class="jarviswidget jarviswidget-color-blueDark" id="wid-id-5" data-widget-editbutton="false"> <!-- widget edit box --> <div class="jarviswidget-editbox"> <!-- This area used as dropdown edit box --> </div> <!-- end widget edit box --> <!-- widget content --> <div class="widget-body no-padding"> <table id="service_path_table" class="table table-striped table-bordered table-hover" width="100%"> <thead> <tr> <th style="text-align:center"data-class="expand" class="col-sm-2"><h1 rel="popover-hover" data-placement="top" data-original-title="Service" data-content="Service is the partition or network segment name for a BU.<br>Click through for historical transitions.<br><br>Services Highlighted in <span class='badge bg-color-yellow'>yellow</span> have transitioned or added within the last 3 days." data-html="true"><strong>Service</strong></h1></th> <th style="text-align:center"><h1 rel="popover-hover" data-placement="top" data-original-title="IP of Service" data-content="The Destination IP address of the corresponding Service<br>is checked from the HUB: hub1: <pre>sh ip bgp x.x.x.x</pre>" data-html="true"><strong>Service IP</strong></h1></th> <th style="text-align:center"data-hide="phone"><h1 rel="popover-hover" data-placement="top" data-original-title="Best Path Router Hostname" data-content="The destination Hostname of the best path router. <br>Hover over name for more detail. <br>Click through for Statseeker Device View." data-html="true"><strong>Service Router</strong></h1></th> <th style="text-align:center"data-hide="phone"><h1 rel="popover-hover" data-placement="top" data-original-title="Service Path Source Location" data-content="Location of running service. <br>Hover for Alternate Paths." data-html="true"><strong>Service Location</strong></h1></th> <th style="text-align:center"data-hide="phone"><h1 rel="popover-hover" data-placement="top" data-original-title="SNMP Location" data-content="SNMP Location field of the best path router." data-html="true"><strong>Route Detail</strong></h1></th> <th style="text-align:center"data-hide="phone,tablet"><h1><strong>Since</strong></h1></th> </tr> </thead> <tbody> {% for row in service_path_table %} <tr> {% if row.service_path_name in created_recent_service_names %} <td align="center" class="success"><h6 rel="popover-hover" data-placement="top" data-original-title="Description" data-content="{{row.service_path_description}}"><strong><a href="/servicepathtable/{{row.service_path_id}}/">{{row.service_path_name}}</a></strong></h6></td> {% elif row.service_path_name in recent_service_names %} <td align="center" class="warning"><h6 rel="popover-hover" data-placement="top" data-original-title="Description" data-content="{{row.service_path_description}}"><strong><a href="/servicepathtable/{{row.service_path_id}}/">{{row.service_path_name}}</a></strong></h6></td> {% else %} <td align="center"><h6 rel="popover-hover" data-placement="top" data-original-title="Description" data-content="{{row.service_path_description}}"><strong><a href="/servicepathtable/{{row.service_path_id}}/">{{row.service_path_name}}</a></strong></h6></td> {% endif %} <td align="center"><h6 rel="popover-hover" data-placement="right" data-original-title="Raw Command Output" data-content="<pre>HTX-JC-HUB-2#{{row.sh_command_output}}</pre>" data-html="true">{{row.service_path_ip}}</td> <td align="center"><h6 rel="popover-hover" data-placement="top" data-original-title="<h4>Quick Router Information</h4>" data-content="<div class='panel-body no-padding'> <table class='table table-bordered table-condensed'> <thead> <tr> <th align='center'>IP</th> <th align='center'>Model</th> <th>Tunnel Count</th> <th>CPU One Minute Average</th> </tr> </thead> <tbody> <tr> <td align='center'>{{row.ip}}</td> <td>{{row.model}}</td> <td align='center'>{{row.tunnel_count}}</td> <td align='center'>{{row.cpu_uti_last_one_min}}%</td> </tr> </tbody> </table> </div>" data-html="true"><a href="http://NIM/cgi/nimc02?sort=&report=116&device={{row.hostname|convert_host}}">{{row.hostname}}</a></h6></td> <td align="center"><h6 rel="popover-hover" data-placement="top" data-original-title="<h4>Alternate Paths</h4>" data-content="<div class='panel-body no-padding'> <table class='table table-bordered table-condensed'> <thead> <tr> <th>jConnect IP</th> <th>Pref</th> <th>Via IP</th> <th>Loopback IP</th> </tr> </thead> <tbody> {% if row.alt_path_0_ip %} <tr> <td>{{row.alt_path_0_ip}}</td> <td>{{row.alt_path_0_local_pref}}</td> <td>{{row.alt_path_0_via_ip}}</td> <td>{{row.alt_path_0_loopback_ip}}</td> </tr> {% endif %} {% if row.alt_path_1_ip %} <tr> <td>{{row.alt_path_1_ip}}</td> <td>{{row.alt_path_1_local_pref}}</td> <td>{{row.alt_path_1_via_ip}}</td> <td>{{row.alt_path_1_loopback_ip}}</td> </tr> {% endif %} {% if row.alt_path_2_ip %} <tr> <td>{{row.alt_path_2_ip}}</td> <td>{{row.alt_path_2_local_pref}}</td> <td>{{row.alt_path_2_via_ip}}</td> <td>{{row.alt_path_2_loopback_ip}}</td> </tr> {% endif %} {% if row.alt_path_3_ip %} <tr> <td>{{row.alt_path_3_ip}}</td> <td>{{row.alt_path_3_local_pref}}</td> <td>{{row.alt_path_3_via_ip}}</td> <td>{{row.alt_path_3_loopback_ip}}</td> </tr> {% endif %} {% if row.alt_path_4_ip %} <tr> <td>{{row.alt_path_4_ip}}</td> <td>{{row.alt_path_4_local_pref}}</td> <td>{{row.alt_path_4_via_ip}}</td> <td>{{row.alt_path_4_loopback_ip}}</td> </tr> {% endif %} </tbody> </table> </div>" data-html="true">{{row.snmp_location|get_city}}</h6></td> <td align="center">{{row.snmp_location}}</td> <td align="center">{{row.date}}</td> </tr> {% endfor %} </tbody> </table> </div> <!-- end widget content --> </div> <!-- end widget div --> </div> <script> $(document).ready(function() { var responsiveHelper_dt_basic = undefined; var responsiveHelper_datatable_fixed_column = undefined; var responsiveHelper_datatable_col_reorder = undefined; var responsiveHelper_datatable_tabletools = undefined; var breakpointDefinition = { tablet : 1024, phone : 480 }; /* TABLETOOLS */ $('#service_path_table').dataTable({ // Tabletools options: // https://datatables.net/extensions/tabletools/button_options "sDom": "<'dt-toolbar'<'col-xs-12 col-sm-6'f><'col-sm-6 col-xs-6 hidden-xs'T>r>"+ "t"+ "<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-sm-6 col-xs-12'p>>", "bPaginate": false, "oTableTools": { "aButtons": [ { "sExtends": "xls", "sTitle": "ETS_Service_Path_Table", }, { "sExtends": "pdf", "sTitle": "ETS_Service_Path_Table", "sPdfMessage": "Service Path Table PDF", "sPdfSize": "letter" }, { "sExtends": "copy", "sButtonText": "Copy to Clipboard", "oSelectorOpts": { filter: "applied", order: "current" } }, { "sExtends": "csv", "sButtonText": "Export to CSV", "sTitle": "ETS_Service_Path_Table", "oSelectorOpts": { filter: "applied", order: "current" } }, { "sExtends": "print", "sButtonText": "Print", "oSelectorOpts": { filter: "applied", order: "current" } } ], "sSwfPath": "http://cdn.datatables.net/tabletools/2.2.2/swf/copy_csv_xls_pdf.swf" }, "autoWidth" : true, "preDrawCallback" : function() { // Initialize the responsive datatables helper once. if (!responsiveHelper_datatable_tabletools) { responsiveHelper_datatable_tabletools = new ResponsiveDatatablesHelper($('#service_path_table'), breakpointDefinition); } }, "rowCallback" : function(nRow) { responsiveHelper_datatable_tabletools.createExpandIcon(nRow); }, "drawCallback" : function(oSettings) { responsiveHelper_datatable_tabletools.respond(); } }); }) </script> 创建切片的相关代码,在这两种情况下,切片从向量的开头一直到Vec<T>

fn deref(&self) -> &[T]

fn deref_mut(&mut self) -> &mut [T]

2 - 有一个optimization in the TcpStream可以避免将内存归零,就像@ Veedrac的替代品一样,但它仅用于self.len而不是read_to_end。执行归零的readperformance reasons

的小分配开始

3 - 切片没有关于矢量大小的信息,因此必须更新矢量长度,否则缓冲区将大于数据并且将使用零。