file_name
large_stringlengths 4
69
| prefix
large_stringlengths 0
26.7k
| suffix
large_stringlengths 0
24.8k
| middle
large_stringlengths 0
2.12k
| fim_type
large_stringclasses 4
values |
---|---|---|---|---|
default.rs
|
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use ast::{MetaItem, Item, Expr};
use codemap::Span;
use ext::base::ExtCtxt;
use ext::build::AstBuilder;
use ext::deriving::generic::*;
pub fn
|
(cx: &ExtCtxt,
span: Span,
mitem: @MetaItem,
in_items: ~[@Item])
-> ~[@Item] {
let trait_def = TraitDef {
cx: cx, span: span,
path: Path::new(~["std", "default", "Default"]),
additional_bounds: ~[],
generics: LifetimeBounds::empty(),
methods: ~[
MethodDef {
name: "default",
generics: LifetimeBounds::empty(),
explicit_self: None,
args: ~[],
ret_ty: Self,
inline: true,
const_nonmatching: false,
combine_substructure: default_substructure
},
]
};
trait_def.expand(mitem, in_items)
}
fn default_substructure(cx: &ExtCtxt, span: Span, substr: &Substructure) -> @Expr {
let default_ident = ~[
cx.ident_of("std"),
cx.ident_of("default"),
cx.ident_of("Default"),
cx.ident_of("default")
];
let default_call = |span| cx.expr_call_global(span, default_ident.clone(), ~[]);
return match *substr.fields {
StaticStruct(_, ref summary) => {
match *summary {
Unnamed(ref fields) => {
if fields.is_empty() {
cx.expr_ident(span, substr.type_ident)
} else {
let exprs = fields.map(|sp| default_call(*sp));
cx.expr_call_ident(span, substr.type_ident, exprs)
}
}
Named(ref fields) => {
let default_fields = fields.map(|&(ident, span)| {
cx.field_imm(span, ident, default_call(span))
});
cx.expr_struct_ident(span, substr.type_ident, default_fields)
}
}
}
StaticEnum(..) => {
cx.span_fatal(span, "`Default` cannot be derived for enums, \
only structs")
}
_ => cx.bug("Non-static method in `deriving(Default)`")
};
}
|
expand_deriving_default
|
identifier_name
|
default.rs
|
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use ast::{MetaItem, Item, Expr};
use codemap::Span;
use ext::base::ExtCtxt;
use ext::build::AstBuilder;
use ext::deriving::generic::*;
pub fn expand_deriving_default(cx: &ExtCtxt,
span: Span,
mitem: @MetaItem,
in_items: ~[@Item])
-> ~[@Item] {
let trait_def = TraitDef {
cx: cx, span: span,
path: Path::new(~["std", "default", "Default"]),
additional_bounds: ~[],
generics: LifetimeBounds::empty(),
methods: ~[
MethodDef {
name: "default",
generics: LifetimeBounds::empty(),
explicit_self: None,
args: ~[],
ret_ty: Self,
inline: true,
const_nonmatching: false,
combine_substructure: default_substructure
},
]
};
trait_def.expand(mitem, in_items)
}
fn default_substructure(cx: &ExtCtxt, span: Span, substr: &Substructure) -> @Expr
|
Named(ref fields) => {
let default_fields = fields.map(|&(ident, span)| {
cx.field_imm(span, ident, default_call(span))
});
cx.expr_struct_ident(span, substr.type_ident, default_fields)
}
}
}
StaticEnum(..) => {
cx.span_fatal(span, "`Default` cannot be derived for enums, \
only structs")
}
_ => cx.bug("Non-static method in `deriving(Default)`")
};
}
|
{
let default_ident = ~[
cx.ident_of("std"),
cx.ident_of("default"),
cx.ident_of("Default"),
cx.ident_of("default")
];
let default_call = |span| cx.expr_call_global(span, default_ident.clone(), ~[]);
return match *substr.fields {
StaticStruct(_, ref summary) => {
match *summary {
Unnamed(ref fields) => {
if fields.is_empty() {
cx.expr_ident(span, substr.type_ident)
} else {
let exprs = fields.map(|sp| default_call(*sp));
cx.expr_call_ident(span, substr.type_ident, exprs)
}
}
|
identifier_body
|
metric.rs
|
/*
Copyright 2015 Google Inc. All rights reserved.
Copyright 2017 Jihyun Yu. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
//! This file implements functions for various S2 measurements.
use libm::{ilogb, ldexp};
use std::f64::consts::{PI, SQRT_2};
use crate::s2::cellid::MAX_LEVEL;
// A metric is a measure for cells. It is used to describe the shape and size
// of cells. They are useful for deciding which cell level to use in order to
// satisfy a given condition (e.g. that cell vertices must be no further than
// "x" apart). You can use the Value(level) method to compute the corresponding
// length or area on the unit sphere for cells at a given level. The minimum
// and maximum bounds are valid for cells at all levels, but they may be
// somewhat conservative for very large cells (e.g. face cells).
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Metric {
// Dim is either 1 or 2, for a 1D or 2D metric respectively.
dim: u8,
// Deriv is the scaling factor for the metric.
deriv: f64,
}
macro_rules! metric {
($name:ident, $dim:expr, $deriv:expr) => {
pub const $name: Metric = Metric {
dim: $dim,
deriv: $deriv,
};
};
}
// Defined metrics.
// Of the projection methods defined in C++, Go only supports the quadratic projection.
// Each cell is bounded by four planes passing through its four edges and
// the center of the sphere. These metrics relate to the angle between each
// pair of opposite bounding planes, or equivalently, between the planes
// corresponding to two different s-values or two different t-values.
metric!(MIN_ANGLE_SPANMETRIC, 1, 4.0 / 3.);
metric!(AVG_ANGLE_SPANMETRIC, 1, PI / 2.);
metric!(MAX_ANGLE_SPANMETRIC, 1, 1.704897179199218452);
// The width of geometric figure is defined as the distance between two
// parallel bounding lines in a given direction. For cells, the minimum
// width is always attained between two opposite edges, and the maximum
// width is attained between two opposite vertices. However, for our
// purposes we redefine the width of a cell as the perpendicular distance
// between a pair of opposite edges. A cell therefore has two widths, one
// in each direction. The minimum width according to this definition agrees
// with the classic geometric one, but the maximum width is different. (The
// maximum geometric width corresponds to MAXDiag defined below.)
//
// The average width in both directions for all cells at level k is approximately
// AVG_WIDTHMETRIC.Value(k).
//
// The width is useful for bounding the minimum or maximum distance from a
// point on one edge of a cell to the closest point on the opposite edge.
// For example, this is useful when growing regions by a fixed distance.
metric!(MIN_WIDTHMETRIC, 1, 2. * SQRT_2 / 3.);
metric!(AVG_WIDTHMETRIC, 1, 1.434523672886099389);
metric!(MAX_WIDTHMETRIC, 1, MAX_ANGLE_SPANMETRIC.deriv);
// The edge length metrics can be used to bound the minimum, maximum,
// or average distance from the center of one cell to the center of one of
// its edge neighbors. In particular, it can be used to bound the distance
// between adjacent cell centers along the space-filling Hilbert curve for
// cells at any given level.
metric!(MIN_EDGEMETRIC, 1, 2. * SQRT_2 / 3.);
metric!(AVG_EDGEMETRIC, 1, 1.459213746386106062);
metric!(MAX_EDGEMETRIC, 1, MAX_ANGLE_SPANMETRIC.deriv);
/// MAX_EDGE_ASPECT is the maximum edge aspect ratio over all cells at any level,
/// where the edge aspect ratio of a cell is defined as the ratio of its longest
/// edge length to its shortest edge length.
pub const MAX_EDGE_ASPECT: f64 = 1.442615274452682920;
metric!(MIN_AREAMETRIC, 2, 8. * SQRT_2 / 9.);
metric!(AVG_AREAMETRIC, 2, 4. * PI / 6.);
metric!(MAX_AREAMETRIC, 2, 2.635799256963161491);
// The maximum diagonal is also the maximum diameter of any cell,
// and also the maximum geometric width (see the comment for widths). For
// example, the distance from an arbitrary point to the closest cell center
// at a given level is at most half the maximum diagonal length.
metric!(MIN_DIAGMETRIC, 1, 8. * SQRT_2 / 9.);
metric!(AVG_DIAGMETRIC, 1, 2.060422738998471683);
metric!(MAX_DIAGMETRIC, 1, 2.438654594434021032);
/// MAX_DIAG_ASPECT is the maximum diagonal aspect ratio over all cells at any
/// level, where the diagonal aspect ratio of a cell is defined as the ratio
/// of its longest diagonal length to its shortest diagonal length.
///TODO: 3f64.sqrt()
pub const MAX_DIAG_ASPECT: f64 = 1.7320508075688772;
impl Metric {
/// value returns the value of the metric at the given level.
pub fn value(&self, level: u8) -> f64
|
/// min_level returns the minimum level such that the metric is at most
/// the given value, or maxLevel (30) if there is no such level.
///
/// For example, MINLevel(0.1) returns the minimum level such that all cell diagonal
/// lengths are 0.1 or smaller. The returned value is always a valid level.
///
/// In C++, this is called GetLevelForMAXValue.
pub fn min_level(&self, val: f64) -> u64 {
if val < 0. {
return MAX_LEVEL;
}
let level = -ilogb(val / self.deriv) >> u64::from(self.dim - 1);
if level > (MAX_LEVEL as i32) {
MAX_LEVEL
} else if level < 0 {
0
} else {
level as u64
}
}
/// max_level returns the maximum level such that the metric is at least
/// the given value, or zero if there is no such level.
///
/// For example, MAXLevel(0.1) returns the maximum level such that all cells have a
/// minimum width of 0.1 or larger. The returned value is always a valid level.
///
/// In C++, this is called GetLevelForMINValue.
pub fn max_level(&self, val: f64) -> u64 {
if val <= 0. {
return MAX_LEVEL;
}
let level = ilogb(self.deriv / val) >> u64::from(self.dim - 1);
if level > (MAX_LEVEL as i32) {
MAX_LEVEL
} else if level < 0 {
0
} else {
level as u64
}
}
/// closest_level returns the level at which the metric has approximately the given
/// value. The return value is always a valid level. For example,
/// AVG_EDGEMETRIC.closest_level(0.1) returns the level at which the average cell edge
/// length is approximately 0.1.
pub fn closest_level(&self, val: f64) -> u64 {
let x = if self.dim == 2 { 2. } else { SQRT_2 };
self.min_level(x * val)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[ignore]
fn test_metric() {
assert_eq!(9, MIN_WIDTHMETRIC.max_level(0.001256));
// Check that the maximum aspect ratio of an individual cell is consistent
// with the global minimums and maximums.
assert!(MAX_EDGE_ASPECT >= 1.);
assert!(MAX_EDGEMETRIC.deriv / MIN_EDGEMETRIC.deriv <= MAX_EDGE_ASPECT);
assert!(MAX_DIAG_ASPECT >= 1.);
assert!(MAX_DIAGMETRIC.deriv / MIN_DIAGMETRIC.deriv <= MAX_DIAG_ASPECT);
// Check that area is consistent with edge and width.
assert!(MIN_WIDTHMETRIC.deriv / MIN_EDGEMETRIC.deriv - 1e-15 <= MIN_AREAMETRIC.deriv);
assert!(MAX_WIDTHMETRIC.deriv / MAX_EDGEMETRIC.deriv + 1e-15 >= MAX_AREAMETRIC.deriv);
}
}
/*
package s2
import (
"math"
"testing"
)
func TestMetric(t *testing.T) {
if got := MinWidthMetric.Deriv*MinEdgeMetric.Deriv - 1e-15; MinAreaMetric.Deriv < got {
t.Errorf("Min Area: %v*%v = %v, want >= %v", MinWidthMetric.Deriv, MinEdgeMetric.Deriv, got, MinAreaMetric.Deriv)
}
if got := MaxWidthMetric.Deriv*MaxEdgeMetric.Deriv + 1e-15; MaxAreaMetric.Deriv > got {
t.Errorf("Max Area: %v*%v = %v, want <= %v", MaxWidthMetric.Deriv, MaxEdgeMetric.Deriv, got, MaxAreaMetric.Deriv)
}
for level := -2; level <= maxLevel+3; level++ {
width := MinWidthMetric.Deriv * math.Pow(2, float64(-level))
if level >= maxLevel+3 {
width = 0
}
// Check boundary cases (exactly equal to a threshold value).
expected := int(math.Max(0, math.Min(maxLevel, float64(level))))
if MinWidthMetric.MinLevel(width)!= expected {
t.Errorf("MinWidthMetric.MinLevel(%v) = %v, want %v", width, MinWidthMetric.MinLevel(width), expected)
}
if MinWidthMetric.MaxLevel(width)!= expected {
t.Errorf("MinWidthMetric.MaxLevel(%v) = %v, want %v", width, MinWidthMetric.MaxLevel(width), expected)
}
if MinWidthMetric.ClosestLevel(width)!= expected {
t.Errorf("MinWidthMetric.ClosestLevel(%v) = %v, want %v", width, MinWidthMetric.ClosestLevel(width), expected)
}
// Also check non-boundary cases.
if got := MinWidthMetric.MinLevel(1.2 * width); got!= expected {
t.Errorf("non-boundary MinWidthMetric.MinLevel(%v) = %v, want %v", 1.2*width, got, expected)
}
if got := MinWidthMetric.MaxLevel(0.8 * width); got!= expected {
t.Errorf("non-boundary MinWidthMetric.MaxLevel(%v) = %v, want %v", 0.8*width, got, expected)
}
if got := MinWidthMetric.ClosestLevel(1.2 * width); got!= expected {
t.Errorf("non-boundary larger MinWidthMetric.ClosestLevel(%v) = %v, want %v", 1.2*width, got, expected)
}
if got := MinWidthMetric.ClosestLevel(0.8 * width); got!= expected {
t.Errorf("non-boundary smaller MinWidthMetric.ClosestLevel(%v) = %v, want %v", 0.8*width, got, expected)
}
}
}
func TestMetricSizeRelations(t *testing.T) {
// check that min <= avg <= max for each metric.
tests := []struct {
min Metric
avg Metric
max Metric
}{
{MinAngleSpanMetric, AvgAngleSpanMetric, MaxAngleSpanMetric},
{MinWidthMetric, AvgWidthMetric, MaxWidthMetric},
{MinEdgeMetric, AvgEdgeMetric, MaxEdgeMetric},
{MinDiagMetric, AvgDiagMetric, MaxDiagMetric},
{MinAreaMetric, AvgAreaMetric, MaxAreaMetric},
}
for _, test := range tests {
if test.min.Deriv > test.avg.Deriv {
t.Errorf("Min %v > Avg %v", test.min.Deriv, test.avg.Deriv)
}
if test.avg.Deriv > test.max.Deriv {
t.Errorf("Avg %v > Max %v", test.avg.Deriv, test.max.Deriv)
}
}
}
*/
|
{
// return math.Ldexp(m.Deriv, -m.Dim*level)
ldexp(self.deriv, -1 * (self.dim as i32) * (level as i32))
}
|
identifier_body
|
metric.rs
|
/*
Copyright 2015 Google Inc. All rights reserved.
Copyright 2017 Jihyun Yu. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
//! This file implements functions for various S2 measurements.
use libm::{ilogb, ldexp};
use std::f64::consts::{PI, SQRT_2};
use crate::s2::cellid::MAX_LEVEL;
// A metric is a measure for cells. It is used to describe the shape and size
// of cells. They are useful for deciding which cell level to use in order to
// satisfy a given condition (e.g. that cell vertices must be no further than
// "x" apart). You can use the Value(level) method to compute the corresponding
// length or area on the unit sphere for cells at a given level. The minimum
// and maximum bounds are valid for cells at all levels, but they may be
// somewhat conservative for very large cells (e.g. face cells).
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Metric {
// Dim is either 1 or 2, for a 1D or 2D metric respectively.
dim: u8,
// Deriv is the scaling factor for the metric.
deriv: f64,
}
macro_rules! metric {
($name:ident, $dim:expr, $deriv:expr) => {
pub const $name: Metric = Metric {
dim: $dim,
deriv: $deriv,
};
};
}
// Defined metrics.
// Of the projection methods defined in C++, Go only supports the quadratic projection.
// Each cell is bounded by four planes passing through its four edges and
// the center of the sphere. These metrics relate to the angle between each
// pair of opposite bounding planes, or equivalently, between the planes
// corresponding to two different s-values or two different t-values.
metric!(MIN_ANGLE_SPANMETRIC, 1, 4.0 / 3.);
metric!(AVG_ANGLE_SPANMETRIC, 1, PI / 2.);
metric!(MAX_ANGLE_SPANMETRIC, 1, 1.704897179199218452);
// The width of geometric figure is defined as the distance between two
// parallel bounding lines in a given direction. For cells, the minimum
// width is always attained between two opposite edges, and the maximum
// width is attained between two opposite vertices. However, for our
// purposes we redefine the width of a cell as the perpendicular distance
// between a pair of opposite edges. A cell therefore has two widths, one
// in each direction. The minimum width according to this definition agrees
// with the classic geometric one, but the maximum width is different. (The
// maximum geometric width corresponds to MAXDiag defined below.)
//
// The average width in both directions for all cells at level k is approximately
// AVG_WIDTHMETRIC.Value(k).
//
// The width is useful for bounding the minimum or maximum distance from a
// point on one edge of a cell to the closest point on the opposite edge.
// For example, this is useful when growing regions by a fixed distance.
metric!(MIN_WIDTHMETRIC, 1, 2. * SQRT_2 / 3.);
metric!(AVG_WIDTHMETRIC, 1, 1.434523672886099389);
metric!(MAX_WIDTHMETRIC, 1, MAX_ANGLE_SPANMETRIC.deriv);
// The edge length metrics can be used to bound the minimum, maximum,
// or average distance from the center of one cell to the center of one of
// its edge neighbors. In particular, it can be used to bound the distance
// between adjacent cell centers along the space-filling Hilbert curve for
// cells at any given level.
metric!(MIN_EDGEMETRIC, 1, 2. * SQRT_2 / 3.);
metric!(AVG_EDGEMETRIC, 1, 1.459213746386106062);
metric!(MAX_EDGEMETRIC, 1, MAX_ANGLE_SPANMETRIC.deriv);
/// MAX_EDGE_ASPECT is the maximum edge aspect ratio over all cells at any level,
/// where the edge aspect ratio of a cell is defined as the ratio of its longest
/// edge length to its shortest edge length.
pub const MAX_EDGE_ASPECT: f64 = 1.442615274452682920;
metric!(MIN_AREAMETRIC, 2, 8. * SQRT_2 / 9.);
metric!(AVG_AREAMETRIC, 2, 4. * PI / 6.);
metric!(MAX_AREAMETRIC, 2, 2.635799256963161491);
// The maximum diagonal is also the maximum diameter of any cell,
// and also the maximum geometric width (see the comment for widths). For
// example, the distance from an arbitrary point to the closest cell center
// at a given level is at most half the maximum diagonal length.
metric!(MIN_DIAGMETRIC, 1, 8. * SQRT_2 / 9.);
metric!(AVG_DIAGMETRIC, 1, 2.060422738998471683);
metric!(MAX_DIAGMETRIC, 1, 2.438654594434021032);
/// MAX_DIAG_ASPECT is the maximum diagonal aspect ratio over all cells at any
/// level, where the diagonal aspect ratio of a cell is defined as the ratio
/// of its longest diagonal length to its shortest diagonal length.
///TODO: 3f64.sqrt()
pub const MAX_DIAG_ASPECT: f64 = 1.7320508075688772;
impl Metric {
/// value returns the value of the metric at the given level.
pub fn value(&self, level: u8) -> f64 {
// return math.Ldexp(m.Deriv, -m.Dim*level)
ldexp(self.deriv, -1 * (self.dim as i32) * (level as i32))
}
/// min_level returns the minimum level such that the metric is at most
/// the given value, or maxLevel (30) if there is no such level.
///
/// For example, MINLevel(0.1) returns the minimum level such that all cell diagonal
/// lengths are 0.1 or smaller. The returned value is always a valid level.
///
/// In C++, this is called GetLevelForMAXValue.
pub fn min_level(&self, val: f64) -> u64 {
if val < 0. {
return MAX_LEVEL;
}
let level = -ilogb(val / self.deriv) >> u64::from(self.dim - 1);
if level > (MAX_LEVEL as i32)
|
else if level < 0 {
0
} else {
level as u64
}
}
/// max_level returns the maximum level such that the metric is at least
/// the given value, or zero if there is no such level.
///
/// For example, MAXLevel(0.1) returns the maximum level such that all cells have a
/// minimum width of 0.1 or larger. The returned value is always a valid level.
///
/// In C++, this is called GetLevelForMINValue.
pub fn max_level(&self, val: f64) -> u64 {
if val <= 0. {
return MAX_LEVEL;
}
let level = ilogb(self.deriv / val) >> u64::from(self.dim - 1);
if level > (MAX_LEVEL as i32) {
MAX_LEVEL
} else if level < 0 {
0
} else {
level as u64
}
}
/// closest_level returns the level at which the metric has approximately the given
/// value. The return value is always a valid level. For example,
/// AVG_EDGEMETRIC.closest_level(0.1) returns the level at which the average cell edge
/// length is approximately 0.1.
pub fn closest_level(&self, val: f64) -> u64 {
let x = if self.dim == 2 { 2. } else { SQRT_2 };
self.min_level(x * val)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[ignore]
fn test_metric() {
assert_eq!(9, MIN_WIDTHMETRIC.max_level(0.001256));
// Check that the maximum aspect ratio of an individual cell is consistent
// with the global minimums and maximums.
assert!(MAX_EDGE_ASPECT >= 1.);
assert!(MAX_EDGEMETRIC.deriv / MIN_EDGEMETRIC.deriv <= MAX_EDGE_ASPECT);
assert!(MAX_DIAG_ASPECT >= 1.);
assert!(MAX_DIAGMETRIC.deriv / MIN_DIAGMETRIC.deriv <= MAX_DIAG_ASPECT);
// Check that area is consistent with edge and width.
assert!(MIN_WIDTHMETRIC.deriv / MIN_EDGEMETRIC.deriv - 1e-15 <= MIN_AREAMETRIC.deriv);
assert!(MAX_WIDTHMETRIC.deriv / MAX_EDGEMETRIC.deriv + 1e-15 >= MAX_AREAMETRIC.deriv);
}
}
/*
package s2
import (
"math"
"testing"
)
func TestMetric(t *testing.T) {
if got := MinWidthMetric.Deriv*MinEdgeMetric.Deriv - 1e-15; MinAreaMetric.Deriv < got {
t.Errorf("Min Area: %v*%v = %v, want >= %v", MinWidthMetric.Deriv, MinEdgeMetric.Deriv, got, MinAreaMetric.Deriv)
}
if got := MaxWidthMetric.Deriv*MaxEdgeMetric.Deriv + 1e-15; MaxAreaMetric.Deriv > got {
t.Errorf("Max Area: %v*%v = %v, want <= %v", MaxWidthMetric.Deriv, MaxEdgeMetric.Deriv, got, MaxAreaMetric.Deriv)
}
for level := -2; level <= maxLevel+3; level++ {
width := MinWidthMetric.Deriv * math.Pow(2, float64(-level))
if level >= maxLevel+3 {
width = 0
}
// Check boundary cases (exactly equal to a threshold value).
expected := int(math.Max(0, math.Min(maxLevel, float64(level))))
if MinWidthMetric.MinLevel(width)!= expected {
t.Errorf("MinWidthMetric.MinLevel(%v) = %v, want %v", width, MinWidthMetric.MinLevel(width), expected)
}
if MinWidthMetric.MaxLevel(width)!= expected {
t.Errorf("MinWidthMetric.MaxLevel(%v) = %v, want %v", width, MinWidthMetric.MaxLevel(width), expected)
}
if MinWidthMetric.ClosestLevel(width)!= expected {
t.Errorf("MinWidthMetric.ClosestLevel(%v) = %v, want %v", width, MinWidthMetric.ClosestLevel(width), expected)
}
// Also check non-boundary cases.
if got := MinWidthMetric.MinLevel(1.2 * width); got!= expected {
t.Errorf("non-boundary MinWidthMetric.MinLevel(%v) = %v, want %v", 1.2*width, got, expected)
}
if got := MinWidthMetric.MaxLevel(0.8 * width); got!= expected {
t.Errorf("non-boundary MinWidthMetric.MaxLevel(%v) = %v, want %v", 0.8*width, got, expected)
}
if got := MinWidthMetric.ClosestLevel(1.2 * width); got!= expected {
t.Errorf("non-boundary larger MinWidthMetric.ClosestLevel(%v) = %v, want %v", 1.2*width, got, expected)
}
if got := MinWidthMetric.ClosestLevel(0.8 * width); got!= expected {
t.Errorf("non-boundary smaller MinWidthMetric.ClosestLevel(%v) = %v, want %v", 0.8*width, got, expected)
}
}
}
func TestMetricSizeRelations(t *testing.T) {
// check that min <= avg <= max for each metric.
tests := []struct {
min Metric
avg Metric
max Metric
}{
{MinAngleSpanMetric, AvgAngleSpanMetric, MaxAngleSpanMetric},
{MinWidthMetric, AvgWidthMetric, MaxWidthMetric},
{MinEdgeMetric, AvgEdgeMetric, MaxEdgeMetric},
{MinDiagMetric, AvgDiagMetric, MaxDiagMetric},
{MinAreaMetric, AvgAreaMetric, MaxAreaMetric},
}
for _, test := range tests {
if test.min.Deriv > test.avg.Deriv {
t.Errorf("Min %v > Avg %v", test.min.Deriv, test.avg.Deriv)
}
if test.avg.Deriv > test.max.Deriv {
t.Errorf("Avg %v > Max %v", test.avg.Deriv, test.max.Deriv)
}
}
}
*/
|
{
MAX_LEVEL
}
|
conditional_block
|
metric.rs
|
/*
Copyright 2015 Google Inc. All rights reserved.
Copyright 2017 Jihyun Yu. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
//! This file implements functions for various S2 measurements.
use libm::{ilogb, ldexp};
use std::f64::consts::{PI, SQRT_2};
use crate::s2::cellid::MAX_LEVEL;
// A metric is a measure for cells. It is used to describe the shape and size
// of cells. They are useful for deciding which cell level to use in order to
// satisfy a given condition (e.g. that cell vertices must be no further than
// "x" apart). You can use the Value(level) method to compute the corresponding
// length or area on the unit sphere for cells at a given level. The minimum
// and maximum bounds are valid for cells at all levels, but they may be
// somewhat conservative for very large cells (e.g. face cells).
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Metric {
// Dim is either 1 or 2, for a 1D or 2D metric respectively.
dim: u8,
// Deriv is the scaling factor for the metric.
deriv: f64,
}
macro_rules! metric {
($name:ident, $dim:expr, $deriv:expr) => {
pub const $name: Metric = Metric {
dim: $dim,
deriv: $deriv,
};
};
}
// Defined metrics.
// Of the projection methods defined in C++, Go only supports the quadratic projection.
// Each cell is bounded by four planes passing through its four edges and
// the center of the sphere. These metrics relate to the angle between each
// pair of opposite bounding planes, or equivalently, between the planes
// corresponding to two different s-values or two different t-values.
metric!(MIN_ANGLE_SPANMETRIC, 1, 4.0 / 3.);
metric!(AVG_ANGLE_SPANMETRIC, 1, PI / 2.);
metric!(MAX_ANGLE_SPANMETRIC, 1, 1.704897179199218452);
// The width of geometric figure is defined as the distance between two
// parallel bounding lines in a given direction. For cells, the minimum
// width is always attained between two opposite edges, and the maximum
// width is attained between two opposite vertices. However, for our
// purposes we redefine the width of a cell as the perpendicular distance
// between a pair of opposite edges. A cell therefore has two widths, one
// in each direction. The minimum width according to this definition agrees
// with the classic geometric one, but the maximum width is different. (The
// maximum geometric width corresponds to MAXDiag defined below.)
//
// The average width in both directions for all cells at level k is approximately
// AVG_WIDTHMETRIC.Value(k).
//
// The width is useful for bounding the minimum or maximum distance from a
// point on one edge of a cell to the closest point on the opposite edge.
// For example, this is useful when growing regions by a fixed distance.
metric!(MIN_WIDTHMETRIC, 1, 2. * SQRT_2 / 3.);
metric!(AVG_WIDTHMETRIC, 1, 1.434523672886099389);
metric!(MAX_WIDTHMETRIC, 1, MAX_ANGLE_SPANMETRIC.deriv);
// The edge length metrics can be used to bound the minimum, maximum,
// or average distance from the center of one cell to the center of one of
// its edge neighbors. In particular, it can be used to bound the distance
// between adjacent cell centers along the space-filling Hilbert curve for
// cells at any given level.
metric!(MIN_EDGEMETRIC, 1, 2. * SQRT_2 / 3.);
metric!(AVG_EDGEMETRIC, 1, 1.459213746386106062);
metric!(MAX_EDGEMETRIC, 1, MAX_ANGLE_SPANMETRIC.deriv);
/// MAX_EDGE_ASPECT is the maximum edge aspect ratio over all cells at any level,
/// where the edge aspect ratio of a cell is defined as the ratio of its longest
/// edge length to its shortest edge length.
pub const MAX_EDGE_ASPECT: f64 = 1.442615274452682920;
metric!(MIN_AREAMETRIC, 2, 8. * SQRT_2 / 9.);
metric!(AVG_AREAMETRIC, 2, 4. * PI / 6.);
metric!(MAX_AREAMETRIC, 2, 2.635799256963161491);
// The maximum diagonal is also the maximum diameter of any cell,
// and also the maximum geometric width (see the comment for widths). For
// example, the distance from an arbitrary point to the closest cell center
// at a given level is at most half the maximum diagonal length.
metric!(MIN_DIAGMETRIC, 1, 8. * SQRT_2 / 9.);
metric!(AVG_DIAGMETRIC, 1, 2.060422738998471683);
metric!(MAX_DIAGMETRIC, 1, 2.438654594434021032);
/// MAX_DIAG_ASPECT is the maximum diagonal aspect ratio over all cells at any
/// level, where the diagonal aspect ratio of a cell is defined as the ratio
/// of its longest diagonal length to its shortest diagonal length.
///TODO: 3f64.sqrt()
pub const MAX_DIAG_ASPECT: f64 = 1.7320508075688772;
impl Metric {
/// value returns the value of the metric at the given level.
pub fn value(&self, level: u8) -> f64 {
// return math.Ldexp(m.Deriv, -m.Dim*level)
ldexp(self.deriv, -1 * (self.dim as i32) * (level as i32))
}
/// min_level returns the minimum level such that the metric is at most
/// the given value, or maxLevel (30) if there is no such level.
///
/// For example, MINLevel(0.1) returns the minimum level such that all cell diagonal
/// lengths are 0.1 or smaller. The returned value is always a valid level.
///
/// In C++, this is called GetLevelForMAXValue.
|
let level = -ilogb(val / self.deriv) >> u64::from(self.dim - 1);
if level > (MAX_LEVEL as i32) {
MAX_LEVEL
} else if level < 0 {
0
} else {
level as u64
}
}
/// max_level returns the maximum level such that the metric is at least
/// the given value, or zero if there is no such level.
///
/// For example, MAXLevel(0.1) returns the maximum level such that all cells have a
/// minimum width of 0.1 or larger. The returned value is always a valid level.
///
/// In C++, this is called GetLevelForMINValue.
pub fn max_level(&self, val: f64) -> u64 {
if val <= 0. {
return MAX_LEVEL;
}
let level = ilogb(self.deriv / val) >> u64::from(self.dim - 1);
if level > (MAX_LEVEL as i32) {
MAX_LEVEL
} else if level < 0 {
0
} else {
level as u64
}
}
/// closest_level returns the level at which the metric has approximately the given
/// value. The return value is always a valid level. For example,
/// AVG_EDGEMETRIC.closest_level(0.1) returns the level at which the average cell edge
/// length is approximately 0.1.
pub fn closest_level(&self, val: f64) -> u64 {
let x = if self.dim == 2 { 2. } else { SQRT_2 };
self.min_level(x * val)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[ignore]
fn test_metric() {
assert_eq!(9, MIN_WIDTHMETRIC.max_level(0.001256));
// Check that the maximum aspect ratio of an individual cell is consistent
// with the global minimums and maximums.
assert!(MAX_EDGE_ASPECT >= 1.);
assert!(MAX_EDGEMETRIC.deriv / MIN_EDGEMETRIC.deriv <= MAX_EDGE_ASPECT);
assert!(MAX_DIAG_ASPECT >= 1.);
assert!(MAX_DIAGMETRIC.deriv / MIN_DIAGMETRIC.deriv <= MAX_DIAG_ASPECT);
// Check that area is consistent with edge and width.
assert!(MIN_WIDTHMETRIC.deriv / MIN_EDGEMETRIC.deriv - 1e-15 <= MIN_AREAMETRIC.deriv);
assert!(MAX_WIDTHMETRIC.deriv / MAX_EDGEMETRIC.deriv + 1e-15 >= MAX_AREAMETRIC.deriv);
}
}
/*
package s2
import (
"math"
"testing"
)
func TestMetric(t *testing.T) {
if got := MinWidthMetric.Deriv*MinEdgeMetric.Deriv - 1e-15; MinAreaMetric.Deriv < got {
t.Errorf("Min Area: %v*%v = %v, want >= %v", MinWidthMetric.Deriv, MinEdgeMetric.Deriv, got, MinAreaMetric.Deriv)
}
if got := MaxWidthMetric.Deriv*MaxEdgeMetric.Deriv + 1e-15; MaxAreaMetric.Deriv > got {
t.Errorf("Max Area: %v*%v = %v, want <= %v", MaxWidthMetric.Deriv, MaxEdgeMetric.Deriv, got, MaxAreaMetric.Deriv)
}
for level := -2; level <= maxLevel+3; level++ {
width := MinWidthMetric.Deriv * math.Pow(2, float64(-level))
if level >= maxLevel+3 {
width = 0
}
// Check boundary cases (exactly equal to a threshold value).
expected := int(math.Max(0, math.Min(maxLevel, float64(level))))
if MinWidthMetric.MinLevel(width)!= expected {
t.Errorf("MinWidthMetric.MinLevel(%v) = %v, want %v", width, MinWidthMetric.MinLevel(width), expected)
}
if MinWidthMetric.MaxLevel(width)!= expected {
t.Errorf("MinWidthMetric.MaxLevel(%v) = %v, want %v", width, MinWidthMetric.MaxLevel(width), expected)
}
if MinWidthMetric.ClosestLevel(width)!= expected {
t.Errorf("MinWidthMetric.ClosestLevel(%v) = %v, want %v", width, MinWidthMetric.ClosestLevel(width), expected)
}
// Also check non-boundary cases.
if got := MinWidthMetric.MinLevel(1.2 * width); got!= expected {
t.Errorf("non-boundary MinWidthMetric.MinLevel(%v) = %v, want %v", 1.2*width, got, expected)
}
if got := MinWidthMetric.MaxLevel(0.8 * width); got!= expected {
t.Errorf("non-boundary MinWidthMetric.MaxLevel(%v) = %v, want %v", 0.8*width, got, expected)
}
if got := MinWidthMetric.ClosestLevel(1.2 * width); got!= expected {
t.Errorf("non-boundary larger MinWidthMetric.ClosestLevel(%v) = %v, want %v", 1.2*width, got, expected)
}
if got := MinWidthMetric.ClosestLevel(0.8 * width); got!= expected {
t.Errorf("non-boundary smaller MinWidthMetric.ClosestLevel(%v) = %v, want %v", 0.8*width, got, expected)
}
}
}
func TestMetricSizeRelations(t *testing.T) {
// check that min <= avg <= max for each metric.
tests := []struct {
min Metric
avg Metric
max Metric
}{
{MinAngleSpanMetric, AvgAngleSpanMetric, MaxAngleSpanMetric},
{MinWidthMetric, AvgWidthMetric, MaxWidthMetric},
{MinEdgeMetric, AvgEdgeMetric, MaxEdgeMetric},
{MinDiagMetric, AvgDiagMetric, MaxDiagMetric},
{MinAreaMetric, AvgAreaMetric, MaxAreaMetric},
}
for _, test := range tests {
if test.min.Deriv > test.avg.Deriv {
t.Errorf("Min %v > Avg %v", test.min.Deriv, test.avg.Deriv)
}
if test.avg.Deriv > test.max.Deriv {
t.Errorf("Avg %v > Max %v", test.avg.Deriv, test.max.Deriv)
}
}
}
*/
|
pub fn min_level(&self, val: f64) -> u64 {
if val < 0. {
return MAX_LEVEL;
}
|
random_line_split
|
metric.rs
|
/*
Copyright 2015 Google Inc. All rights reserved.
Copyright 2017 Jihyun Yu. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
//! This file implements functions for various S2 measurements.
use libm::{ilogb, ldexp};
use std::f64::consts::{PI, SQRT_2};
use crate::s2::cellid::MAX_LEVEL;
// A metric is a measure for cells. It is used to describe the shape and size
// of cells. They are useful for deciding which cell level to use in order to
// satisfy a given condition (e.g. that cell vertices must be no further than
// "x" apart). You can use the Value(level) method to compute the corresponding
// length or area on the unit sphere for cells at a given level. The minimum
// and maximum bounds are valid for cells at all levels, but they may be
// somewhat conservative for very large cells (e.g. face cells).
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Metric {
// Dim is either 1 or 2, for a 1D or 2D metric respectively.
dim: u8,
// Deriv is the scaling factor for the metric.
deriv: f64,
}
macro_rules! metric {
($name:ident, $dim:expr, $deriv:expr) => {
pub const $name: Metric = Metric {
dim: $dim,
deriv: $deriv,
};
};
}
// Defined metrics.
// Of the projection methods defined in C++, Go only supports the quadratic projection.
// Each cell is bounded by four planes passing through its four edges and
// the center of the sphere. These metrics relate to the angle between each
// pair of opposite bounding planes, or equivalently, between the planes
// corresponding to two different s-values or two different t-values.
metric!(MIN_ANGLE_SPANMETRIC, 1, 4.0 / 3.);
metric!(AVG_ANGLE_SPANMETRIC, 1, PI / 2.);
metric!(MAX_ANGLE_SPANMETRIC, 1, 1.704897179199218452);
// The width of geometric figure is defined as the distance between two
// parallel bounding lines in a given direction. For cells, the minimum
// width is always attained between two opposite edges, and the maximum
// width is attained between two opposite vertices. However, for our
// purposes we redefine the width of a cell as the perpendicular distance
// between a pair of opposite edges. A cell therefore has two widths, one
// in each direction. The minimum width according to this definition agrees
// with the classic geometric one, but the maximum width is different. (The
// maximum geometric width corresponds to MAXDiag defined below.)
//
// The average width in both directions for all cells at level k is approximately
// AVG_WIDTHMETRIC.Value(k).
//
// The width is useful for bounding the minimum or maximum distance from a
// point on one edge of a cell to the closest point on the opposite edge.
// For example, this is useful when growing regions by a fixed distance.
metric!(MIN_WIDTHMETRIC, 1, 2. * SQRT_2 / 3.);
metric!(AVG_WIDTHMETRIC, 1, 1.434523672886099389);
metric!(MAX_WIDTHMETRIC, 1, MAX_ANGLE_SPANMETRIC.deriv);
// The edge length metrics can be used to bound the minimum, maximum,
// or average distance from the center of one cell to the center of one of
// its edge neighbors. In particular, it can be used to bound the distance
// between adjacent cell centers along the space-filling Hilbert curve for
// cells at any given level.
metric!(MIN_EDGEMETRIC, 1, 2. * SQRT_2 / 3.);
metric!(AVG_EDGEMETRIC, 1, 1.459213746386106062);
metric!(MAX_EDGEMETRIC, 1, MAX_ANGLE_SPANMETRIC.deriv);
/// MAX_EDGE_ASPECT is the maximum edge aspect ratio over all cells at any level,
/// where the edge aspect ratio of a cell is defined as the ratio of its longest
/// edge length to its shortest edge length.
pub const MAX_EDGE_ASPECT: f64 = 1.442615274452682920;
metric!(MIN_AREAMETRIC, 2, 8. * SQRT_2 / 9.);
metric!(AVG_AREAMETRIC, 2, 4. * PI / 6.);
metric!(MAX_AREAMETRIC, 2, 2.635799256963161491);
// The maximum diagonal is also the maximum diameter of any cell,
// and also the maximum geometric width (see the comment for widths). For
// example, the distance from an arbitrary point to the closest cell center
// at a given level is at most half the maximum diagonal length.
metric!(MIN_DIAGMETRIC, 1, 8. * SQRT_2 / 9.);
metric!(AVG_DIAGMETRIC, 1, 2.060422738998471683);
metric!(MAX_DIAGMETRIC, 1, 2.438654594434021032);
/// MAX_DIAG_ASPECT is the maximum diagonal aspect ratio over all cells at any
/// level, where the diagonal aspect ratio of a cell is defined as the ratio
/// of its longest diagonal length to its shortest diagonal length.
///TODO: 3f64.sqrt()
pub const MAX_DIAG_ASPECT: f64 = 1.7320508075688772;
impl Metric {
/// value returns the value of the metric at the given level.
pub fn value(&self, level: u8) -> f64 {
// return math.Ldexp(m.Deriv, -m.Dim*level)
ldexp(self.deriv, -1 * (self.dim as i32) * (level as i32))
}
/// min_level returns the minimum level such that the metric is at most
/// the given value, or maxLevel (30) if there is no such level.
///
/// For example, MINLevel(0.1) returns the minimum level such that all cell diagonal
/// lengths are 0.1 or smaller. The returned value is always a valid level.
///
/// In C++, this is called GetLevelForMAXValue.
pub fn
|
(&self, val: f64) -> u64 {
if val < 0. {
return MAX_LEVEL;
}
let level = -ilogb(val / self.deriv) >> u64::from(self.dim - 1);
if level > (MAX_LEVEL as i32) {
MAX_LEVEL
} else if level < 0 {
0
} else {
level as u64
}
}
/// max_level returns the maximum level such that the metric is at least
/// the given value, or zero if there is no such level.
///
/// For example, MAXLevel(0.1) returns the maximum level such that all cells have a
/// minimum width of 0.1 or larger. The returned value is always a valid level.
///
/// In C++, this is called GetLevelForMINValue.
pub fn max_level(&self, val: f64) -> u64 {
if val <= 0. {
return MAX_LEVEL;
}
let level = ilogb(self.deriv / val) >> u64::from(self.dim - 1);
if level > (MAX_LEVEL as i32) {
MAX_LEVEL
} else if level < 0 {
0
} else {
level as u64
}
}
/// closest_level returns the level at which the metric has approximately the given
/// value. The return value is always a valid level. For example,
/// AVG_EDGEMETRIC.closest_level(0.1) returns the level at which the average cell edge
/// length is approximately 0.1.
pub fn closest_level(&self, val: f64) -> u64 {
let x = if self.dim == 2 { 2. } else { SQRT_2 };
self.min_level(x * val)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[ignore]
fn test_metric() {
assert_eq!(9, MIN_WIDTHMETRIC.max_level(0.001256));
// Check that the maximum aspect ratio of an individual cell is consistent
// with the global minimums and maximums.
assert!(MAX_EDGE_ASPECT >= 1.);
assert!(MAX_EDGEMETRIC.deriv / MIN_EDGEMETRIC.deriv <= MAX_EDGE_ASPECT);
assert!(MAX_DIAG_ASPECT >= 1.);
assert!(MAX_DIAGMETRIC.deriv / MIN_DIAGMETRIC.deriv <= MAX_DIAG_ASPECT);
// Check that area is consistent with edge and width.
assert!(MIN_WIDTHMETRIC.deriv / MIN_EDGEMETRIC.deriv - 1e-15 <= MIN_AREAMETRIC.deriv);
assert!(MAX_WIDTHMETRIC.deriv / MAX_EDGEMETRIC.deriv + 1e-15 >= MAX_AREAMETRIC.deriv);
}
}
/*
package s2
import (
"math"
"testing"
)
func TestMetric(t *testing.T) {
if got := MinWidthMetric.Deriv*MinEdgeMetric.Deriv - 1e-15; MinAreaMetric.Deriv < got {
t.Errorf("Min Area: %v*%v = %v, want >= %v", MinWidthMetric.Deriv, MinEdgeMetric.Deriv, got, MinAreaMetric.Deriv)
}
if got := MaxWidthMetric.Deriv*MaxEdgeMetric.Deriv + 1e-15; MaxAreaMetric.Deriv > got {
t.Errorf("Max Area: %v*%v = %v, want <= %v", MaxWidthMetric.Deriv, MaxEdgeMetric.Deriv, got, MaxAreaMetric.Deriv)
}
for level := -2; level <= maxLevel+3; level++ {
width := MinWidthMetric.Deriv * math.Pow(2, float64(-level))
if level >= maxLevel+3 {
width = 0
}
// Check boundary cases (exactly equal to a threshold value).
expected := int(math.Max(0, math.Min(maxLevel, float64(level))))
if MinWidthMetric.MinLevel(width)!= expected {
t.Errorf("MinWidthMetric.MinLevel(%v) = %v, want %v", width, MinWidthMetric.MinLevel(width), expected)
}
if MinWidthMetric.MaxLevel(width)!= expected {
t.Errorf("MinWidthMetric.MaxLevel(%v) = %v, want %v", width, MinWidthMetric.MaxLevel(width), expected)
}
if MinWidthMetric.ClosestLevel(width)!= expected {
t.Errorf("MinWidthMetric.ClosestLevel(%v) = %v, want %v", width, MinWidthMetric.ClosestLevel(width), expected)
}
// Also check non-boundary cases.
if got := MinWidthMetric.MinLevel(1.2 * width); got!= expected {
t.Errorf("non-boundary MinWidthMetric.MinLevel(%v) = %v, want %v", 1.2*width, got, expected)
}
if got := MinWidthMetric.MaxLevel(0.8 * width); got!= expected {
t.Errorf("non-boundary MinWidthMetric.MaxLevel(%v) = %v, want %v", 0.8*width, got, expected)
}
if got := MinWidthMetric.ClosestLevel(1.2 * width); got!= expected {
t.Errorf("non-boundary larger MinWidthMetric.ClosestLevel(%v) = %v, want %v", 1.2*width, got, expected)
}
if got := MinWidthMetric.ClosestLevel(0.8 * width); got!= expected {
t.Errorf("non-boundary smaller MinWidthMetric.ClosestLevel(%v) = %v, want %v", 0.8*width, got, expected)
}
}
}
func TestMetricSizeRelations(t *testing.T) {
// check that min <= avg <= max for each metric.
tests := []struct {
min Metric
avg Metric
max Metric
}{
{MinAngleSpanMetric, AvgAngleSpanMetric, MaxAngleSpanMetric},
{MinWidthMetric, AvgWidthMetric, MaxWidthMetric},
{MinEdgeMetric, AvgEdgeMetric, MaxEdgeMetric},
{MinDiagMetric, AvgDiagMetric, MaxDiagMetric},
{MinAreaMetric, AvgAreaMetric, MaxAreaMetric},
}
for _, test := range tests {
if test.min.Deriv > test.avg.Deriv {
t.Errorf("Min %v > Avg %v", test.min.Deriv, test.avg.Deriv)
}
if test.avg.Deriv > test.max.Deriv {
t.Errorf("Avg %v > Max %v", test.avg.Deriv, test.max.Deriv)
}
}
}
*/
|
min_level
|
identifier_name
|
sort.rs
|
use std::collections::BTreeMap;
use std::convert::AsRef;
pub struct Sorter;
// ToDo: merge with Indexing?
impl Sorter {
pub fn sort<T, R>(values: R) -> Vec<T>
where
T: Clone + Ord,
R: AsRef<Vec<T>>,
{
let values: &Vec<T> = values.as_ref();
// Clone all elements
let mut result = values.clone();
result.sort();
result
}
/// Sort by values returning indexer and sorted values
pub fn argsort<T, R>(values: R) -> (Vec<usize>, Vec<T>)
where
T: Clone + Ord,
R: AsRef<Vec<T>>,
{
let values: &Vec<T> = values.as_ref();
let mut map: BTreeMap<T, Vec<usize>> = BTreeMap::new();
for (i, v) in values.iter().enumerate() {
let e = map.entry(v.clone()).or_insert(Vec::<usize>::new());
e.push(i);
}
let mut sorted: Vec<T> = Vec::with_capacity(values.len());
let mut indexer: Vec<usize> = Vec::with_capacity(values.len());
for (k, locs) in map.into_iter() {
for loc in locs {
sorted.push(k.clone());
indexer.push(loc);
}
}
(indexer, sorted)
}
/// Sort values by key returning sorted key and values
pub fn sort_by<T, U>(keys: &Vec<T>, values: &Vec<U>) -> (Vec<T>, Vec<U>)
where
T: Clone + Ord,
U: Clone,
{
let mut map: BTreeMap<T, Vec<U>> = BTreeMap::new();
for (k, v) in keys.iter().zip(values) {
let e = map.entry(k.clone()).or_insert(Vec::<U>::new());
e.push(v.clone());
}
let mut sorted_keys: Vec<T> = Vec::with_capacity(values.len());
let mut sorted_values: Vec<U> = Vec::with_capacity(values.len());
for (k, vals) in map.into_iter() {
for v in vals {
sorted_keys.push(k.clone());
sorted_values.push(v);
}
}
(sorted_keys, sorted_values)
}
}
#[cfg(test)]
mod tests {
use super::Sorter;
#[test]
fn test_argsort_empty() {
let (indexer, sorted) = Sorter::argsort(&Vec::<i64>::new());
assert_eq!(indexer, vec![]);
assert_eq!(sorted, vec![]);
}
#[test]
fn test_argsort_int() {
let (indexer, sorted) = Sorter::argsort(&vec![2, 2, 2, 3, 3]);
assert_eq!(indexer, vec![0, 1, 2, 3, 4]);
assert_eq!(sorted, vec![2, 2, 2, 3, 3]);
let (indexer, sorted) = Sorter::argsort(&vec![4, 2, 1, 3, 3]);
assert_eq!(indexer, vec![2, 1, 3, 4, 0]);
assert_eq!(sorted, vec![1, 2, 3, 3, 4]);
}
#[test]
fn test_argsort_str() {
let (indexer, sorted) = Sorter::argsort(&vec!["b", "bb", "a", "bb"]);
assert_eq!(indexer, vec![2, 0, 1, 3]);
assert_eq!(sorted, vec!["a", "b", "bb", "bb"]);
}
#[test]
fn test_sort_by_int() {
let (keys, vals) = Sorter::sort_by(&vec![5, 4, 3, 2, 1], &vec![1, 2, 3, 4, 5]);
assert_eq!(keys, vec![1, 2, 3, 4, 5]);
assert_eq!(vals, vec![5, 4, 3, 2, 1]);
}
#[test]
fn test_sort_by_int_dup()
|
#[test]
fn test_sort_by_int_float() {
let (keys, vals) = Sorter::sort_by(&vec![3, 2, 1, 4, 1], &vec![1.1, 2.1, 3.1, 4.1, 5.1]);
assert_eq!(keys, vec![1, 1, 2, 3, 4]);
assert_eq!(vals, vec![3.1, 5.1, 2.1, 1.1, 4.1]);
}
}
|
{
let (keys, vals) = Sorter::sort_by(&vec![3, 3, 1, 1, 1], &vec![1, 2, 3, 4, 5]);
assert_eq!(keys, vec![1, 1, 1, 3, 3]);
assert_eq!(vals, vec![3, 4, 5, 1, 2]);
}
|
identifier_body
|
sort.rs
|
use std::collections::BTreeMap;
use std::convert::AsRef;
pub struct Sorter;
// ToDo: merge with Indexing?
impl Sorter {
pub fn sort<T, R>(values: R) -> Vec<T>
where
T: Clone + Ord,
R: AsRef<Vec<T>>,
{
let values: &Vec<T> = values.as_ref();
// Clone all elements
let mut result = values.clone();
result.sort();
result
}
/// Sort by values returning indexer and sorted values
pub fn argsort<T, R>(values: R) -> (Vec<usize>, Vec<T>)
where
T: Clone + Ord,
R: AsRef<Vec<T>>,
{
let values: &Vec<T> = values.as_ref();
let mut map: BTreeMap<T, Vec<usize>> = BTreeMap::new();
for (i, v) in values.iter().enumerate() {
let e = map.entry(v.clone()).or_insert(Vec::<usize>::new());
e.push(i);
}
let mut sorted: Vec<T> = Vec::with_capacity(values.len());
let mut indexer: Vec<usize> = Vec::with_capacity(values.len());
for (k, locs) in map.into_iter() {
for loc in locs {
|
}
(indexer, sorted)
}
/// Sort values by key returning sorted key and values
pub fn sort_by<T, U>(keys: &Vec<T>, values: &Vec<U>) -> (Vec<T>, Vec<U>)
where
T: Clone + Ord,
U: Clone,
{
let mut map: BTreeMap<T, Vec<U>> = BTreeMap::new();
for (k, v) in keys.iter().zip(values) {
let e = map.entry(k.clone()).or_insert(Vec::<U>::new());
e.push(v.clone());
}
let mut sorted_keys: Vec<T> = Vec::with_capacity(values.len());
let mut sorted_values: Vec<U> = Vec::with_capacity(values.len());
for (k, vals) in map.into_iter() {
for v in vals {
sorted_keys.push(k.clone());
sorted_values.push(v);
}
}
(sorted_keys, sorted_values)
}
}
#[cfg(test)]
mod tests {
use super::Sorter;
#[test]
fn test_argsort_empty() {
let (indexer, sorted) = Sorter::argsort(&Vec::<i64>::new());
assert_eq!(indexer, vec![]);
assert_eq!(sorted, vec![]);
}
#[test]
fn test_argsort_int() {
let (indexer, sorted) = Sorter::argsort(&vec![2, 2, 2, 3, 3]);
assert_eq!(indexer, vec![0, 1, 2, 3, 4]);
assert_eq!(sorted, vec![2, 2, 2, 3, 3]);
let (indexer, sorted) = Sorter::argsort(&vec![4, 2, 1, 3, 3]);
assert_eq!(indexer, vec![2, 1, 3, 4, 0]);
assert_eq!(sorted, vec![1, 2, 3, 3, 4]);
}
#[test]
fn test_argsort_str() {
let (indexer, sorted) = Sorter::argsort(&vec!["b", "bb", "a", "bb"]);
assert_eq!(indexer, vec![2, 0, 1, 3]);
assert_eq!(sorted, vec!["a", "b", "bb", "bb"]);
}
#[test]
fn test_sort_by_int() {
let (keys, vals) = Sorter::sort_by(&vec![5, 4, 3, 2, 1], &vec![1, 2, 3, 4, 5]);
assert_eq!(keys, vec![1, 2, 3, 4, 5]);
assert_eq!(vals, vec![5, 4, 3, 2, 1]);
}
#[test]
fn test_sort_by_int_dup() {
let (keys, vals) = Sorter::sort_by(&vec![3, 3, 1, 1, 1], &vec![1, 2, 3, 4, 5]);
assert_eq!(keys, vec![1, 1, 1, 3, 3]);
assert_eq!(vals, vec![3, 4, 5, 1, 2]);
}
#[test]
fn test_sort_by_int_float() {
let (keys, vals) = Sorter::sort_by(&vec![3, 2, 1, 4, 1], &vec![1.1, 2.1, 3.1, 4.1, 5.1]);
assert_eq!(keys, vec![1, 1, 2, 3, 4]);
assert_eq!(vals, vec![3.1, 5.1, 2.1, 1.1, 4.1]);
}
}
|
sorted.push(k.clone());
indexer.push(loc);
}
|
random_line_split
|
sort.rs
|
use std::collections::BTreeMap;
use std::convert::AsRef;
pub struct Sorter;
// ToDo: merge with Indexing?
impl Sorter {
pub fn sort<T, R>(values: R) -> Vec<T>
where
T: Clone + Ord,
R: AsRef<Vec<T>>,
{
let values: &Vec<T> = values.as_ref();
// Clone all elements
let mut result = values.clone();
result.sort();
result
}
/// Sort by values returning indexer and sorted values
pub fn argsort<T, R>(values: R) -> (Vec<usize>, Vec<T>)
where
T: Clone + Ord,
R: AsRef<Vec<T>>,
{
let values: &Vec<T> = values.as_ref();
let mut map: BTreeMap<T, Vec<usize>> = BTreeMap::new();
for (i, v) in values.iter().enumerate() {
let e = map.entry(v.clone()).or_insert(Vec::<usize>::new());
e.push(i);
}
let mut sorted: Vec<T> = Vec::with_capacity(values.len());
let mut indexer: Vec<usize> = Vec::with_capacity(values.len());
for (k, locs) in map.into_iter() {
for loc in locs {
sorted.push(k.clone());
indexer.push(loc);
}
}
(indexer, sorted)
}
/// Sort values by key returning sorted key and values
pub fn sort_by<T, U>(keys: &Vec<T>, values: &Vec<U>) -> (Vec<T>, Vec<U>)
where
T: Clone + Ord,
U: Clone,
{
let mut map: BTreeMap<T, Vec<U>> = BTreeMap::new();
for (k, v) in keys.iter().zip(values) {
let e = map.entry(k.clone()).or_insert(Vec::<U>::new());
e.push(v.clone());
}
let mut sorted_keys: Vec<T> = Vec::with_capacity(values.len());
let mut sorted_values: Vec<U> = Vec::with_capacity(values.len());
for (k, vals) in map.into_iter() {
for v in vals {
sorted_keys.push(k.clone());
sorted_values.push(v);
}
}
(sorted_keys, sorted_values)
}
}
#[cfg(test)]
mod tests {
use super::Sorter;
#[test]
fn
|
() {
let (indexer, sorted) = Sorter::argsort(&Vec::<i64>::new());
assert_eq!(indexer, vec![]);
assert_eq!(sorted, vec![]);
}
#[test]
fn test_argsort_int() {
let (indexer, sorted) = Sorter::argsort(&vec![2, 2, 2, 3, 3]);
assert_eq!(indexer, vec![0, 1, 2, 3, 4]);
assert_eq!(sorted, vec![2, 2, 2, 3, 3]);
let (indexer, sorted) = Sorter::argsort(&vec![4, 2, 1, 3, 3]);
assert_eq!(indexer, vec![2, 1, 3, 4, 0]);
assert_eq!(sorted, vec![1, 2, 3, 3, 4]);
}
#[test]
fn test_argsort_str() {
let (indexer, sorted) = Sorter::argsort(&vec!["b", "bb", "a", "bb"]);
assert_eq!(indexer, vec![2, 0, 1, 3]);
assert_eq!(sorted, vec!["a", "b", "bb", "bb"]);
}
#[test]
fn test_sort_by_int() {
let (keys, vals) = Sorter::sort_by(&vec![5, 4, 3, 2, 1], &vec![1, 2, 3, 4, 5]);
assert_eq!(keys, vec![1, 2, 3, 4, 5]);
assert_eq!(vals, vec![5, 4, 3, 2, 1]);
}
#[test]
fn test_sort_by_int_dup() {
let (keys, vals) = Sorter::sort_by(&vec![3, 3, 1, 1, 1], &vec![1, 2, 3, 4, 5]);
assert_eq!(keys, vec![1, 1, 1, 3, 3]);
assert_eq!(vals, vec![3, 4, 5, 1, 2]);
}
#[test]
fn test_sort_by_int_float() {
let (keys, vals) = Sorter::sort_by(&vec![3, 2, 1, 4, 1], &vec![1.1, 2.1, 3.1, 4.1, 5.1]);
assert_eq!(keys, vec![1, 1, 2, 3, 4]);
assert_eq!(vals, vec![3.1, 5.1, 2.1, 1.1, 4.1]);
}
}
|
test_argsort_empty
|
identifier_name
|
letter_frequency.rs
|
// http://rosettacode.org/wiki/Letter_frequency
#![cfg_attr(not(test), feature(io))]
#[cfg(not(test))]
use std::fs::File;
#[cfg(not(test))]
use std::io::{BufReader, Read};
use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};
fn count_chars<T>(chars: T) -> HashMap<char, usize>
where T : Iterator<Item=char>
|
for letter in chars {
match map.entry(letter) {
Vacant(entry) => { entry.insert(1); },
Occupied(mut entry) => { *entry.get_mut() += 1; }
};
}
map
}
#[cfg(not(test))]
fn main() {
let file = File::open("resources/unixdict.txt").unwrap();
let reader = BufReader::new(file);
println!("{:?}", count_chars(reader.chars().map(|c| c.unwrap())));
}
#[test]
fn test_empty() {
let map = count_chars("".chars());
assert!(map.len() == 0);
}
#[test]
fn test_basic() {
let map = count_chars("aaaabbbbc".chars());
assert!(map.len() == 3);
assert!(map[&'a'] == 4);
assert!(map[&'b'] == 4);
assert!(map[&'c'] == 1);
}
|
{
let mut map: HashMap<char, usize> = HashMap::new();
|
random_line_split
|
letter_frequency.rs
|
// http://rosettacode.org/wiki/Letter_frequency
#![cfg_attr(not(test), feature(io))]
#[cfg(not(test))]
use std::fs::File;
#[cfg(not(test))]
use std::io::{BufReader, Read};
use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};
fn count_chars<T>(chars: T) -> HashMap<char, usize>
where T : Iterator<Item=char>
{
let mut map: HashMap<char, usize> = HashMap::new();
for letter in chars {
match map.entry(letter) {
Vacant(entry) => { entry.insert(1); },
Occupied(mut entry) => { *entry.get_mut() += 1; }
};
}
map
}
#[cfg(not(test))]
fn main() {
let file = File::open("resources/unixdict.txt").unwrap();
let reader = BufReader::new(file);
println!("{:?}", count_chars(reader.chars().map(|c| c.unwrap())));
}
#[test]
fn test_empty() {
let map = count_chars("".chars());
assert!(map.len() == 0);
}
#[test]
fn
|
() {
let map = count_chars("aaaabbbbc".chars());
assert!(map.len() == 3);
assert!(map[&'a'] == 4);
assert!(map[&'b'] == 4);
assert!(map[&'c'] == 1);
}
|
test_basic
|
identifier_name
|
letter_frequency.rs
|
// http://rosettacode.org/wiki/Letter_frequency
#![cfg_attr(not(test), feature(io))]
#[cfg(not(test))]
use std::fs::File;
#[cfg(not(test))]
use std::io::{BufReader, Read};
use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};
fn count_chars<T>(chars: T) -> HashMap<char, usize>
where T : Iterator<Item=char>
|
#[cfg(not(test))]
fn main() {
let file = File::open("resources/unixdict.txt").unwrap();
let reader = BufReader::new(file);
println!("{:?}", count_chars(reader.chars().map(|c| c.unwrap())));
}
#[test]
fn test_empty() {
let map = count_chars("".chars());
assert!(map.len() == 0);
}
#[test]
fn test_basic() {
let map = count_chars("aaaabbbbc".chars());
assert!(map.len() == 3);
assert!(map[&'a'] == 4);
assert!(map[&'b'] == 4);
assert!(map[&'c'] == 1);
}
|
{
let mut map: HashMap<char, usize> = HashMap::new();
for letter in chars {
match map.entry(letter) {
Vacant(entry) => { entry.insert(1); },
Occupied(mut entry) => { *entry.get_mut() += 1; }
};
}
map
}
|
identifier_body
|
letter_frequency.rs
|
// http://rosettacode.org/wiki/Letter_frequency
#![cfg_attr(not(test), feature(io))]
#[cfg(not(test))]
use std::fs::File;
#[cfg(not(test))]
use std::io::{BufReader, Read};
use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};
fn count_chars<T>(chars: T) -> HashMap<char, usize>
where T : Iterator<Item=char>
{
let mut map: HashMap<char, usize> = HashMap::new();
for letter in chars {
match map.entry(letter) {
Vacant(entry) =>
|
,
Occupied(mut entry) => { *entry.get_mut() += 1; }
};
}
map
}
#[cfg(not(test))]
fn main() {
let file = File::open("resources/unixdict.txt").unwrap();
let reader = BufReader::new(file);
println!("{:?}", count_chars(reader.chars().map(|c| c.unwrap())));
}
#[test]
fn test_empty() {
let map = count_chars("".chars());
assert!(map.len() == 0);
}
#[test]
fn test_basic() {
let map = count_chars("aaaabbbbc".chars());
assert!(map.len() == 3);
assert!(map[&'a'] == 4);
assert!(map[&'b'] == 4);
assert!(map[&'c'] == 1);
}
|
{ entry.insert(1); }
|
conditional_block
|
simple_earley.rs
|
use bongo::grammar::{
build, BaseElementTypes, Elem, Grammar, NonTerminal, ProdElement, Terminal,
};
use bongo::parsers::earley::parse;
use bongo::parsers::{tree::TreeOwner, Token};
use bongo::start_grammar::wrap_grammar_with_start;
use bongo::utils::Name;
fn main()
|
ProdElement::new_with_name(
Name::new("contents"),
Elem::NonTerm(a_nt.clone()),
),
ProdElement::new_empty(Elem::Term(rp_t.clone())),
],
);
});
})
.unwrap();
let g = wrap_grammar_with_start(g).unwrap();
eprintln!("Grammar: {}", g.to_pretty());
let tree: TreeOwner<_, &'static str> = TreeOwner::new();
let node = parse(
&g,
&tree.handle(),
vec![
Token::new(lp_t.clone(), "("),
Token::new(v_t.clone(), "Hello!"),
Token::new(rp_t.clone(), ")"),
],
)
.unwrap();
println!("{}", node.to_dot());
}
|
{
let a_nt = NonTerminal::new("a");
let lp_t = Terminal::new("LPAREN");
let rp_t = Terminal::new("RPAREN");
let v_t = Terminal::new("VALUE");
let g: Grammar<BaseElementTypes> = build(&a_nt, |b| {
b.add_rule(&a_nt, |br| {
br.add_prod_with_elems(
&Name::new("value"),
(),
vec![ProdElement::new_with_name(
Name::new("val"),
Elem::Term(v_t.clone()),
)],
)
.add_prod_with_elems(
&Name::new("parens"),
(),
vec![
ProdElement::new_empty(Elem::Term(lp_t.clone())),
|
identifier_body
|
simple_earley.rs
|
use bongo::grammar::{
build, BaseElementTypes, Elem, Grammar, NonTerminal, ProdElement, Terminal,
};
use bongo::parsers::earley::parse;
use bongo::parsers::{tree::TreeOwner, Token};
use bongo::start_grammar::wrap_grammar_with_start;
use bongo::utils::Name;
fn main() {
let a_nt = NonTerminal::new("a");
let lp_t = Terminal::new("LPAREN");
let rp_t = Terminal::new("RPAREN");
let v_t = Terminal::new("VALUE");
let g: Grammar<BaseElementTypes> = build(&a_nt, |b| {
b.add_rule(&a_nt, |br| {
br.add_prod_with_elems(
&Name::new("value"),
(),
vec![ProdElement::new_with_name(
Name::new("val"),
|
)
.add_prod_with_elems(
&Name::new("parens"),
(),
vec![
ProdElement::new_empty(Elem::Term(lp_t.clone())),
ProdElement::new_with_name(
Name::new("contents"),
Elem::NonTerm(a_nt.clone()),
),
ProdElement::new_empty(Elem::Term(rp_t.clone())),
],
);
});
})
.unwrap();
let g = wrap_grammar_with_start(g).unwrap();
eprintln!("Grammar: {}", g.to_pretty());
let tree: TreeOwner<_, &'static str> = TreeOwner::new();
let node = parse(
&g,
&tree.handle(),
vec![
Token::new(lp_t.clone(), "("),
Token::new(v_t.clone(), "Hello!"),
Token::new(rp_t.clone(), ")"),
],
)
.unwrap();
println!("{}", node.to_dot());
}
|
Elem::Term(v_t.clone()),
)],
|
random_line_split
|
simple_earley.rs
|
use bongo::grammar::{
build, BaseElementTypes, Elem, Grammar, NonTerminal, ProdElement, Terminal,
};
use bongo::parsers::earley::parse;
use bongo::parsers::{tree::TreeOwner, Token};
use bongo::start_grammar::wrap_grammar_with_start;
use bongo::utils::Name;
fn
|
() {
let a_nt = NonTerminal::new("a");
let lp_t = Terminal::new("LPAREN");
let rp_t = Terminal::new("RPAREN");
let v_t = Terminal::new("VALUE");
let g: Grammar<BaseElementTypes> = build(&a_nt, |b| {
b.add_rule(&a_nt, |br| {
br.add_prod_with_elems(
&Name::new("value"),
(),
vec![ProdElement::new_with_name(
Name::new("val"),
Elem::Term(v_t.clone()),
)],
)
.add_prod_with_elems(
&Name::new("parens"),
(),
vec![
ProdElement::new_empty(Elem::Term(lp_t.clone())),
ProdElement::new_with_name(
Name::new("contents"),
Elem::NonTerm(a_nt.clone()),
),
ProdElement::new_empty(Elem::Term(rp_t.clone())),
],
);
});
})
.unwrap();
let g = wrap_grammar_with_start(g).unwrap();
eprintln!("Grammar: {}", g.to_pretty());
let tree: TreeOwner<_, &'static str> = TreeOwner::new();
let node = parse(
&g,
&tree.handle(),
vec![
Token::new(lp_t.clone(), "("),
Token::new(v_t.clone(), "Hello!"),
Token::new(rp_t.clone(), ")"),
],
)
.unwrap();
println!("{}", node.to_dot());
}
|
main
|
identifier_name
|
main.rs
|
fn main() {
let s1 = gives_ownership(); // gives_ownership 将返回值
// 转移给 s1
let s2 = String::from("hello"); // s2 进入作用域
let s3 = takes_and_gives_back(s2); // s2 被移动到
// takes_and_gives_back 中,
// 它也将返回值移给 s3
} // 这里, s3 移出作用域并被丢弃。s2 也移出作用域,但已被移走,
// 所以什么也不会发生。s1 离开作用域并被丢弃
fn gives_ownership() -> String { // gives_ownership 会将
// 返回值移动给
// 调用它的函数
let some_string = String::from("yours"); // some_string 进入作用域.
some_string // 返回 some_string
// 并移出给调用的函数
//
}
// takes_and_gives_back 将传入字符串并返回该值
fn takes_and_gives_back(a_string: String) -> String { // a_string 进入作用域
//
a_string // 返回 a_string 并移出给调用的函数
}
|
identifier_body
|
||
main.rs
|
fn main() {
let s1 = gives_ownership(); // gives_ownership 将返回值
// 转移给 s1
let s2 = String::from("hello"); // s2 进入作用域
let s3 = takes_and_gives_back(s2); // s2 被移动到
// takes_and_gives_back 中,
// 它也将返回值移给 s3
} // 这里, s3 移出作用域并被丢弃。s2 也移出作用域,但已被移走,
// 所以什么也不会发生。s1 离开作用域并被丢弃
fn gives_ownership() -> String { // gives_ownership 会将
// 返回值移动给
// 调用它的函数
let some_string = String::from("yours"); // some_string 进入作用域.
some_string // 返回 some_string
// 并移出给调用的函数
//
}
// takes_and_gives_back 将传入字符串并返回该值
fn takes_and_gives_back(a_string: String) -> String { // a_string 进入作用域
//
a_string // 返回 a_string 并移出给调用的函数
}
|
identifier_name
|
||
main.rs
|
fn main() {
let s1 = gives_ownership(); // gives_ownership 将返回值
// 转移给 s1
let s2 = String::from("hello"); // s2 进入作用域
let s3 = takes_and_gives_back(s2); // s2 被移动到
// takes_and_gives_back 中,
// 它也将返回值移给 s3
} // 这里, s3 移出作用域并被丢弃。s2 也移出作用域,但已被移走,
// 所以什么也不会发生。s1 离开作用域并被丢弃
|
let some_string = String::from("yours"); // some_string 进入作用域.
some_string // 返回 some_string
// 并移出给调用的函数
//
}
// takes_and_gives_back 将传入字符串并返回该值
fn takes_and_gives_back(a_string: String) -> String { // a_string 进入作用域
//
a_string // 返回 a_string 并移出给调用的函数
}
|
fn gives_ownership() -> String { // gives_ownership 会将
// 返回值移动给
// 调用它的函数
|
random_line_split
|
lib.rs
|
//! Nursery for slog-rs
//!
//! This crate is forever unstable, and contains things that
//! at a given moment are useful but not final.
#![warn(missing_docs)]
extern crate slog;
use slog::*;
use std::result;
/// `Drain` that switches destination of error
///
/// Logs everything to drain `D1`, but in case of it reporting an error,
/// switching to `D2`. If `D2` returns an error too, `Failover` will return
/// an error.
pub struct Failover<D1: Drain, D2: Drain>
{
drain1: D1,
drain2: D2,
}
impl<D1: Drain, D2: Drain, O> Failover<D1, D2>
where
D1 : Drain<Ok = O>,
D2 : Drain<Ok = O>,
{
|
/// Create `Failover`
pub fn new(drain1: D1, drain2: D2) -> Self {
Failover {
drain1: drain1,
drain2: drain2,
}
}
}
impl<D1, D2, E2, O> Drain for Failover<D1, D2>
where
D1 : Drain<Ok = O>,
D2 : Drain<Ok = O>,
{
type Ok = O;
type Err = D2::Err;
fn log(&self,
info: &Record,
logger_values: &OwnedKVList)
-> result::Result<Self::Ok, Self::Err> {
match self.drain1.log(info, logger_values) {
Ok(ok) => Ok(ok),
Err(_) => self.drain2.log(info, logger_values),
}
}
}
/// Failover logging to secondary drain on primary's failure
///
/// Create `Failover` drain
pub fn failover<D1: Drain, D2: Drain, O>(d1: D1, d2: D2) -> Failover<D1, D2>
where
D1 : Drain<Ok = O>,
D2 : Drain<Ok = O>,
{
Failover::new(d1, d2)
}
|
random_line_split
|
|
lib.rs
|
//! Nursery for slog-rs
//!
//! This crate is forever unstable, and contains things that
//! at a given moment are useful but not final.
#![warn(missing_docs)]
extern crate slog;
use slog::*;
use std::result;
/// `Drain` that switches destination of error
///
/// Logs everything to drain `D1`, but in case of it reporting an error,
/// switching to `D2`. If `D2` returns an error too, `Failover` will return
/// an error.
pub struct
|
<D1: Drain, D2: Drain>
{
drain1: D1,
drain2: D2,
}
impl<D1: Drain, D2: Drain, O> Failover<D1, D2>
where
D1 : Drain<Ok = O>,
D2 : Drain<Ok = O>,
{
/// Create `Failover`
pub fn new(drain1: D1, drain2: D2) -> Self {
Failover {
drain1: drain1,
drain2: drain2,
}
}
}
impl<D1, D2, E2, O> Drain for Failover<D1, D2>
where
D1 : Drain<Ok = O>,
D2 : Drain<Ok = O>,
{
type Ok = O;
type Err = D2::Err;
fn log(&self,
info: &Record,
logger_values: &OwnedKVList)
-> result::Result<Self::Ok, Self::Err> {
match self.drain1.log(info, logger_values) {
Ok(ok) => Ok(ok),
Err(_) => self.drain2.log(info, logger_values),
}
}
}
/// Failover logging to secondary drain on primary's failure
///
/// Create `Failover` drain
pub fn failover<D1: Drain, D2: Drain, O>(d1: D1, d2: D2) -> Failover<D1, D2>
where
D1 : Drain<Ok = O>,
D2 : Drain<Ok = O>,
{
Failover::new(d1, d2)
}
|
Failover
|
identifier_name
|
lib.rs
|
//! Nursery for slog-rs
//!
//! This crate is forever unstable, and contains things that
//! at a given moment are useful but not final.
#![warn(missing_docs)]
extern crate slog;
use slog::*;
use std::result;
/// `Drain` that switches destination of error
///
/// Logs everything to drain `D1`, but in case of it reporting an error,
/// switching to `D2`. If `D2` returns an error too, `Failover` will return
/// an error.
pub struct Failover<D1: Drain, D2: Drain>
{
drain1: D1,
drain2: D2,
}
impl<D1: Drain, D2: Drain, O> Failover<D1, D2>
where
D1 : Drain<Ok = O>,
D2 : Drain<Ok = O>,
{
/// Create `Failover`
pub fn new(drain1: D1, drain2: D2) -> Self {
Failover {
drain1: drain1,
drain2: drain2,
}
}
}
impl<D1, D2, E2, O> Drain for Failover<D1, D2>
where
D1 : Drain<Ok = O>,
D2 : Drain<Ok = O>,
{
type Ok = O;
type Err = D2::Err;
fn log(&self,
info: &Record,
logger_values: &OwnedKVList)
-> result::Result<Self::Ok, Self::Err>
|
}
/// Failover logging to secondary drain on primary's failure
///
/// Create `Failover` drain
pub fn failover<D1: Drain, D2: Drain, O>(d1: D1, d2: D2) -> Failover<D1, D2>
where
D1 : Drain<Ok = O>,
D2 : Drain<Ok = O>,
{
Failover::new(d1, d2)
}
|
{
match self.drain1.log(info, logger_values) {
Ok(ok) => Ok(ok),
Err(_) => self.drain2.log(info, logger_values),
}
}
|
identifier_body
|
deriving-cmp-generic-struct-enum.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
|
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// no-pretty-expanded FIXME #15189
// pretty-expanded FIXME #23616
#[derive(PartialEq, Eq, PartialOrd, Ord)]
enum ES<T> {
ES1 { x: T },
ES2 { x: T, y: T }
}
pub fn main() {
let (es11, es12, es21, es22) = (ES::ES1 {
x: 1
}, ES::ES1 {
x: 2
}, ES::ES2 {
x: 1,
y: 1
}, ES::ES2 {
x: 1,
y: 2
});
// in order for both PartialOrd and Ord
let ess = [es11, es12, es21, es22];
for (i, es1) in ess.iter().enumerate() {
for (j, es2) in ess.iter().enumerate() {
let ord = i.cmp(&j);
let eq = i == j;
let (lt, le) = (i < j, i <= j);
let (gt, ge) = (i > j, i >= j);
// PartialEq
assert_eq!(*es1 == *es2, eq);
assert_eq!(*es1!= *es2,!eq);
// PartialOrd
assert_eq!(*es1 < *es2, lt);
assert_eq!(*es1 > *es2, gt);
assert_eq!(*es1 <= *es2, le);
assert_eq!(*es1 >= *es2, ge);
// Ord
assert_eq!(es1.cmp(es2), ord);
}
}
}
|
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
random_line_split
|
deriving-cmp-generic-struct-enum.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// no-pretty-expanded FIXME #15189
// pretty-expanded FIXME #23616
#[derive(PartialEq, Eq, PartialOrd, Ord)]
enum ES<T> {
ES1 { x: T },
ES2 { x: T, y: T }
}
pub fn main()
|
let eq = i == j;
let (lt, le) = (i < j, i <= j);
let (gt, ge) = (i > j, i >= j);
// PartialEq
assert_eq!(*es1 == *es2, eq);
assert_eq!(*es1!= *es2,!eq);
// PartialOrd
assert_eq!(*es1 < *es2, lt);
assert_eq!(*es1 > *es2, gt);
assert_eq!(*es1 <= *es2, le);
assert_eq!(*es1 >= *es2, ge);
// Ord
assert_eq!(es1.cmp(es2), ord);
}
}
}
|
{
let (es11, es12, es21, es22) = (ES::ES1 {
x: 1
}, ES::ES1 {
x: 2
}, ES::ES2 {
x: 1,
y: 1
}, ES::ES2 {
x: 1,
y: 2
});
// in order for both PartialOrd and Ord
let ess = [es11, es12, es21, es22];
for (i, es1) in ess.iter().enumerate() {
for (j, es2) in ess.iter().enumerate() {
let ord = i.cmp(&j);
|
identifier_body
|
deriving-cmp-generic-struct-enum.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// no-pretty-expanded FIXME #15189
// pretty-expanded FIXME #23616
#[derive(PartialEq, Eq, PartialOrd, Ord)]
enum ES<T> {
ES1 { x: T },
ES2 { x: T, y: T }
}
pub fn
|
() {
let (es11, es12, es21, es22) = (ES::ES1 {
x: 1
}, ES::ES1 {
x: 2
}, ES::ES2 {
x: 1,
y: 1
}, ES::ES2 {
x: 1,
y: 2
});
// in order for both PartialOrd and Ord
let ess = [es11, es12, es21, es22];
for (i, es1) in ess.iter().enumerate() {
for (j, es2) in ess.iter().enumerate() {
let ord = i.cmp(&j);
let eq = i == j;
let (lt, le) = (i < j, i <= j);
let (gt, ge) = (i > j, i >= j);
// PartialEq
assert_eq!(*es1 == *es2, eq);
assert_eq!(*es1!= *es2,!eq);
// PartialOrd
assert_eq!(*es1 < *es2, lt);
assert_eq!(*es1 > *es2, gt);
assert_eq!(*es1 <= *es2, le);
assert_eq!(*es1 >= *es2, ge);
// Ord
assert_eq!(es1.cmp(es2), ord);
}
}
}
|
main
|
identifier_name
|
expr-if-fail.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
fn
|
() { let x = if false { fail!() } else { 10 }; assert!((x == 10)); }
fn test_else_fail() {
let x = if true { 10 } else { fail!() };
assert!((x == 10));
}
fn test_elseif_fail() {
let x = if false { 0 } else if false { fail!() } else { 10 };
assert!((x == 10));
}
pub fn main() { test_if_fail(); test_else_fail(); test_elseif_fail(); }
|
test_if_fail
|
identifier_name
|
expr-if-fail.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
fn test_if_fail()
|
fn test_else_fail() {
let x = if true { 10 } else { fail!() };
assert!((x == 10));
}
fn test_elseif_fail() {
let x = if false { 0 } else if false { fail!() } else { 10 };
assert!((x == 10));
}
pub fn main() { test_if_fail(); test_else_fail(); test_elseif_fail(); }
|
{ let x = if false { fail!() } else { 10 }; assert!((x == 10)); }
|
identifier_body
|
expr-if-fail.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
// option. This file may not be copied, modified, or distributed
// except according to those terms.
fn test_if_fail() { let x = if false { fail!() } else { 10 }; assert!((x == 10)); }
fn test_else_fail() {
let x = if true { 10 } else { fail!() };
assert!((x == 10));
}
fn test_elseif_fail() {
let x = if false { 0 } else if false { fail!() } else { 10 };
assert!((x == 10));
}
pub fn main() { test_if_fail(); test_else_fail(); test_elseif_fail(); }
|
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
random_line_split
|
expr-if-fail.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
fn test_if_fail() { let x = if false { fail!() } else { 10 }; assert!((x == 10)); }
fn test_else_fail() {
let x = if true
|
else { fail!() };
assert!((x == 10));
}
fn test_elseif_fail() {
let x = if false { 0 } else if false { fail!() } else { 10 };
assert!((x == 10));
}
pub fn main() { test_if_fail(); test_else_fail(); test_elseif_fail(); }
|
{ 10 }
|
conditional_block
|
closure-syntax.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(dead_code)]
fn
|
<T>() {}
trait Bar1 {}
impl Bar1 for proc() {}
trait Bar2 {}
impl Bar2 for proc(): Send {}
trait Bar3 {}
impl<'b> Bar3 for <'a>|&'a int|: 'b + Send -> &'a int {}
trait Bar4 {}
impl Bar4 for proc<'a>(&'a int) -> &'a int {}
struct Foo<'a> {
a: ||: 'a,
b: ||:'static,
c: <'b>||: 'a,
d: ||: 'a + Share,
e: <'b>|int|: 'a + Share -> &'b f32,
f: proc(),
g: proc():'static + Share,
h: proc<'b>(int): Share -> &'b f32,
}
fn f<'a>(a: &'a int, f: <'b>|&'b int| -> &'b int) -> &'a int {
f(a)
}
fn g<'a>(a: &'a int, f: proc<'b>(&'b int) -> &'b int) -> &'a int {
f(a)
}
struct A;
impl A {
fn foo<T>(&self) {}
}
fn bar<'b>() {
foo::<||>();
foo::<|| -> ()>();
foo::<||:>();
foo::<||:'b>();
foo::<||:'b + Share>();
foo::<||:Share>();
foo::< <'a>|int, f32, &'a int|:'b + Share -> &'a int>();
foo::<proc()>();
foo::<proc() -> ()>();
foo::<proc():>();
foo::<proc():'static>();
foo::<proc():Share>();
foo::<proc<'a>(int, f32, &'a int):'static + Share -> &'a int>();
foo::<<'a>||>();
// issue #11209
let _: ||: 'b; // for comparison
let _: <'a> ||;
let _: Option<||:'b>;
let _: Option<<'a>||>;
let _: Option< <'a>||>;
// issue #11210
let _: ||:'static;
let a = A;
a.foo::<<'a>||>();
}
struct B<T>;
impl<'b> B<<'a>||: 'b> {}
pub fn main() {
}
|
foo
|
identifier_name
|
closure-syntax.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(dead_code)]
fn foo<T>() {}
trait Bar1 {}
impl Bar1 for proc() {}
trait Bar2 {}
impl Bar2 for proc(): Send {}
trait Bar3 {}
impl<'b> Bar3 for <'a>|&'a int|: 'b + Send -> &'a int {}
trait Bar4 {}
impl Bar4 for proc<'a>(&'a int) -> &'a int {}
|
struct Foo<'a> {
a: ||: 'a,
b: ||:'static,
c: <'b>||: 'a,
d: ||: 'a + Share,
e: <'b>|int|: 'a + Share -> &'b f32,
f: proc(),
g: proc():'static + Share,
h: proc<'b>(int): Share -> &'b f32,
}
fn f<'a>(a: &'a int, f: <'b>|&'b int| -> &'b int) -> &'a int {
f(a)
}
fn g<'a>(a: &'a int, f: proc<'b>(&'b int) -> &'b int) -> &'a int {
f(a)
}
struct A;
impl A {
fn foo<T>(&self) {}
}
fn bar<'b>() {
foo::<||>();
foo::<|| -> ()>();
foo::<||:>();
foo::<||:'b>();
foo::<||:'b + Share>();
foo::<||:Share>();
foo::< <'a>|int, f32, &'a int|:'b + Share -> &'a int>();
foo::<proc()>();
foo::<proc() -> ()>();
foo::<proc():>();
foo::<proc():'static>();
foo::<proc():Share>();
foo::<proc<'a>(int, f32, &'a int):'static + Share -> &'a int>();
foo::<<'a>||>();
// issue #11209
let _: ||: 'b; // for comparison
let _: <'a> ||;
let _: Option<||:'b>;
let _: Option<<'a>||>;
let _: Option< <'a>||>;
// issue #11210
let _: ||:'static;
let a = A;
a.foo::<<'a>||>();
}
struct B<T>;
impl<'b> B<<'a>||: 'b> {}
pub fn main() {
}
|
random_line_split
|
|
closure-syntax.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(dead_code)]
fn foo<T>()
|
trait Bar1 {}
impl Bar1 for proc() {}
trait Bar2 {}
impl Bar2 for proc(): Send {}
trait Bar3 {}
impl<'b> Bar3 for <'a>|&'a int|: 'b + Send -> &'a int {}
trait Bar4 {}
impl Bar4 for proc<'a>(&'a int) -> &'a int {}
struct Foo<'a> {
a: ||: 'a,
b: ||:'static,
c: <'b>||: 'a,
d: ||: 'a + Share,
e: <'b>|int|: 'a + Share -> &'b f32,
f: proc(),
g: proc():'static + Share,
h: proc<'b>(int): Share -> &'b f32,
}
fn f<'a>(a: &'a int, f: <'b>|&'b int| -> &'b int) -> &'a int {
f(a)
}
fn g<'a>(a: &'a int, f: proc<'b>(&'b int) -> &'b int) -> &'a int {
f(a)
}
struct A;
impl A {
fn foo<T>(&self) {}
}
fn bar<'b>() {
foo::<||>();
foo::<|| -> ()>();
foo::<||:>();
foo::<||:'b>();
foo::<||:'b + Share>();
foo::<||:Share>();
foo::< <'a>|int, f32, &'a int|:'b + Share -> &'a int>();
foo::<proc()>();
foo::<proc() -> ()>();
foo::<proc():>();
foo::<proc():'static>();
foo::<proc():Share>();
foo::<proc<'a>(int, f32, &'a int):'static + Share -> &'a int>();
foo::<<'a>||>();
// issue #11209
let _: ||: 'b; // for comparison
let _: <'a> ||;
let _: Option<||:'b>;
let _: Option<<'a>||>;
let _: Option< <'a>||>;
// issue #11210
let _: ||:'static;
let a = A;
a.foo::<<'a>||>();
}
struct B<T>;
impl<'b> B<<'a>||: 'b> {}
pub fn main() {
}
|
{}
|
identifier_body
|
main.rs
|
extern crate piston; // piston core
extern crate graphics; // piston graphics
extern crate glutin_window; // opengl context creation
extern crate opengl_graphics; // opengl binding
//extern crate find_folder; // for finding our assets folder.
extern crate time;
extern crate rand;
extern crate ncollide; // 2d/3d/nd collision detection stuff
extern crate nalgebra; // has some neat matrices, vectors and points
extern crate rustc_serialize; // for ai::nn
// for json
extern crate serde;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
use piston::window::WindowSettings;
use piston::event_loop::*; // Generic eventloop
use piston::input::*;
use glutin_window::GlutinWindow as Window;
use opengl_graphics::{GlGraphics, OpenGL};
use nalgebra::{Vector2};
mod snake;
mod state;
mod input;
mod ai;
mod food;
mod geometry;
pub struct App {
gl: GlGraphics, // OpenGL drawing backend.
world_state: state::WorldState,
should_render: bool,
window_rect: Vector2<u32>,
}
impl App {
fn render(&mut self, args: &RenderArgs) {
if self.should_render {
self.window_rect = Vector2::new(args.width, args.height);
use graphics::*;
const BLACK: [f32; 4] = [0.0, 0.0, 0.0, 1.0];
let world_state = &self.world_state;
let viewport = args.viewport();
self.gl
.draw(viewport, |c, gl| {
// Clear the screen.
clear(BLACK, gl);
for snake in &world_state.snakes {
snake.render(&c, gl, &args);
}
});
}
}
fn update(&mut self, args: &UpdateArgs) {
self.world_state.window_rect = self.window_rect;
self.world_state.update(args);
}
}
fn main() {
// Change this to OpenGL::V2_1 if not working.
|
let opengl = OpenGL::V3_2;
let (width, height) = (1280, 720);
// Create an Glutin window.
let mut window: Window = WindowSettings::new("Snake Game", [width, height])
.opengl(opengl)
.exit_on_esc(true)
.vsync(true)
.fullscreen(false)
.build()
.unwrap();
// Create a new game and run it.
let mut app: App = App {
gl: GlGraphics::new(opengl),
world_state: state::WorldState::default(),
should_render: true,
window_rect: Vector2::new(width, height),
};
// You can change these
app.world_state.speed = 20.0;
app.world_state.snake_length = 3;
for _ in 0..4 { // Try increasing this a lot and remove printlns.
let snake = snake::Snake::new(geometry::random_point_within(app.window_rect), 3, 20.0);
app.world_state.snakes.push(snake);
}
// Add 10 snakes. with default length 2 and width 10
//default:.max_fps(60).ups(120)
let mut events = Events::new(EventSettings::new()).max_fps(60).ups(120);
while let Some(e) = events.next(&mut window) {
if let Some(r) = e.render_args() {
app.render(&r);
}
if let Some(u) = e.update_args() {
// Simulate lag:
// std::thread::sleep(std::time::Duration::new(0, 1000_000_00));
app.update(&u);
}
}
}
|
random_line_split
|
|
main.rs
|
extern crate piston; // piston core
extern crate graphics; // piston graphics
extern crate glutin_window; // opengl context creation
extern crate opengl_graphics; // opengl binding
//extern crate find_folder; // for finding our assets folder.
extern crate time;
extern crate rand;
extern crate ncollide; // 2d/3d/nd collision detection stuff
extern crate nalgebra; // has some neat matrices, vectors and points
extern crate rustc_serialize; // for ai::nn
// for json
extern crate serde;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
use piston::window::WindowSettings;
use piston::event_loop::*; // Generic eventloop
use piston::input::*;
use glutin_window::GlutinWindow as Window;
use opengl_graphics::{GlGraphics, OpenGL};
use nalgebra::{Vector2};
mod snake;
mod state;
mod input;
mod ai;
mod food;
mod geometry;
pub struct App {
gl: GlGraphics, // OpenGL drawing backend.
world_state: state::WorldState,
should_render: bool,
window_rect: Vector2<u32>,
}
impl App {
fn render(&mut self, args: &RenderArgs) {
if self.should_render {
self.window_rect = Vector2::new(args.width, args.height);
use graphics::*;
const BLACK: [f32; 4] = [0.0, 0.0, 0.0, 1.0];
let world_state = &self.world_state;
let viewport = args.viewport();
self.gl
.draw(viewport, |c, gl| {
// Clear the screen.
clear(BLACK, gl);
for snake in &world_state.snakes {
snake.render(&c, gl, &args);
}
});
}
}
fn update(&mut self, args: &UpdateArgs) {
self.world_state.window_rect = self.window_rect;
self.world_state.update(args);
}
}
fn main() {
// Change this to OpenGL::V2_1 if not working.
let opengl = OpenGL::V3_2;
let (width, height) = (1280, 720);
// Create an Glutin window.
let mut window: Window = WindowSettings::new("Snake Game", [width, height])
.opengl(opengl)
.exit_on_esc(true)
.vsync(true)
.fullscreen(false)
.build()
.unwrap();
// Create a new game and run it.
let mut app: App = App {
gl: GlGraphics::new(opengl),
world_state: state::WorldState::default(),
should_render: true,
window_rect: Vector2::new(width, height),
};
// You can change these
app.world_state.speed = 20.0;
app.world_state.snake_length = 3;
for _ in 0..4 { // Try increasing this a lot and remove printlns.
let snake = snake::Snake::new(geometry::random_point_within(app.window_rect), 3, 20.0);
app.world_state.snakes.push(snake);
}
// Add 10 snakes. with default length 2 and width 10
//default:.max_fps(60).ups(120)
let mut events = Events::new(EventSettings::new()).max_fps(60).ups(120);
while let Some(e) = events.next(&mut window) {
if let Some(r) = e.render_args()
|
if let Some(u) = e.update_args() {
// Simulate lag:
// std::thread::sleep(std::time::Duration::new(0, 1000_000_00));
app.update(&u);
}
}
}
|
{
app.render(&r);
}
|
conditional_block
|
main.rs
|
extern crate piston; // piston core
extern crate graphics; // piston graphics
extern crate glutin_window; // opengl context creation
extern crate opengl_graphics; // opengl binding
//extern crate find_folder; // for finding our assets folder.
extern crate time;
extern crate rand;
extern crate ncollide; // 2d/3d/nd collision detection stuff
extern crate nalgebra; // has some neat matrices, vectors and points
extern crate rustc_serialize; // for ai::nn
// for json
extern crate serde;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
use piston::window::WindowSettings;
use piston::event_loop::*; // Generic eventloop
use piston::input::*;
use glutin_window::GlutinWindow as Window;
use opengl_graphics::{GlGraphics, OpenGL};
use nalgebra::{Vector2};
mod snake;
mod state;
mod input;
mod ai;
mod food;
mod geometry;
pub struct App {
gl: GlGraphics, // OpenGL drawing backend.
world_state: state::WorldState,
should_render: bool,
window_rect: Vector2<u32>,
}
impl App {
fn
|
(&mut self, args: &RenderArgs) {
if self.should_render {
self.window_rect = Vector2::new(args.width, args.height);
use graphics::*;
const BLACK: [f32; 4] = [0.0, 0.0, 0.0, 1.0];
let world_state = &self.world_state;
let viewport = args.viewport();
self.gl
.draw(viewport, |c, gl| {
// Clear the screen.
clear(BLACK, gl);
for snake in &world_state.snakes {
snake.render(&c, gl, &args);
}
});
}
}
fn update(&mut self, args: &UpdateArgs) {
self.world_state.window_rect = self.window_rect;
self.world_state.update(args);
}
}
fn main() {
// Change this to OpenGL::V2_1 if not working.
let opengl = OpenGL::V3_2;
let (width, height) = (1280, 720);
// Create an Glutin window.
let mut window: Window = WindowSettings::new("Snake Game", [width, height])
.opengl(opengl)
.exit_on_esc(true)
.vsync(true)
.fullscreen(false)
.build()
.unwrap();
// Create a new game and run it.
let mut app: App = App {
gl: GlGraphics::new(opengl),
world_state: state::WorldState::default(),
should_render: true,
window_rect: Vector2::new(width, height),
};
// You can change these
app.world_state.speed = 20.0;
app.world_state.snake_length = 3;
for _ in 0..4 { // Try increasing this a lot and remove printlns.
let snake = snake::Snake::new(geometry::random_point_within(app.window_rect), 3, 20.0);
app.world_state.snakes.push(snake);
}
// Add 10 snakes. with default length 2 and width 10
//default:.max_fps(60).ups(120)
let mut events = Events::new(EventSettings::new()).max_fps(60).ups(120);
while let Some(e) = events.next(&mut window) {
if let Some(r) = e.render_args() {
app.render(&r);
}
if let Some(u) = e.update_args() {
// Simulate lag:
// std::thread::sleep(std::time::Duration::new(0, 1000_000_00));
app.update(&u);
}
}
}
|
render
|
identifier_name
|
main.rs
|
extern crate piston; // piston core
extern crate graphics; // piston graphics
extern crate glutin_window; // opengl context creation
extern crate opengl_graphics; // opengl binding
//extern crate find_folder; // for finding our assets folder.
extern crate time;
extern crate rand;
extern crate ncollide; // 2d/3d/nd collision detection stuff
extern crate nalgebra; // has some neat matrices, vectors and points
extern crate rustc_serialize; // for ai::nn
// for json
extern crate serde;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
use piston::window::WindowSettings;
use piston::event_loop::*; // Generic eventloop
use piston::input::*;
use glutin_window::GlutinWindow as Window;
use opengl_graphics::{GlGraphics, OpenGL};
use nalgebra::{Vector2};
mod snake;
mod state;
mod input;
mod ai;
mod food;
mod geometry;
pub struct App {
gl: GlGraphics, // OpenGL drawing backend.
world_state: state::WorldState,
should_render: bool,
window_rect: Vector2<u32>,
}
impl App {
fn render(&mut self, args: &RenderArgs) {
if self.should_render {
self.window_rect = Vector2::new(args.width, args.height);
use graphics::*;
const BLACK: [f32; 4] = [0.0, 0.0, 0.0, 1.0];
let world_state = &self.world_state;
let viewport = args.viewport();
self.gl
.draw(viewport, |c, gl| {
// Clear the screen.
clear(BLACK, gl);
for snake in &world_state.snakes {
snake.render(&c, gl, &args);
}
});
}
}
fn update(&mut self, args: &UpdateArgs)
|
}
fn main() {
// Change this to OpenGL::V2_1 if not working.
let opengl = OpenGL::V3_2;
let (width, height) = (1280, 720);
// Create an Glutin window.
let mut window: Window = WindowSettings::new("Snake Game", [width, height])
.opengl(opengl)
.exit_on_esc(true)
.vsync(true)
.fullscreen(false)
.build()
.unwrap();
// Create a new game and run it.
let mut app: App = App {
gl: GlGraphics::new(opengl),
world_state: state::WorldState::default(),
should_render: true,
window_rect: Vector2::new(width, height),
};
// You can change these
app.world_state.speed = 20.0;
app.world_state.snake_length = 3;
for _ in 0..4 { // Try increasing this a lot and remove printlns.
let snake = snake::Snake::new(geometry::random_point_within(app.window_rect), 3, 20.0);
app.world_state.snakes.push(snake);
}
// Add 10 snakes. with default length 2 and width 10
//default:.max_fps(60).ups(120)
let mut events = Events::new(EventSettings::new()).max_fps(60).ups(120);
while let Some(e) = events.next(&mut window) {
if let Some(r) = e.render_args() {
app.render(&r);
}
if let Some(u) = e.update_args() {
// Simulate lag:
// std::thread::sleep(std::time::Duration::new(0, 1000_000_00));
app.update(&u);
}
}
}
|
{
self.world_state.window_rect = self.window_rect;
self.world_state.update(args);
}
|
identifier_body
|
unit-return.rs
|
// aux-build:unit-return.rs
#![crate_name = "foo"]
extern crate unit_return;
// @has 'foo/fn.f0.html' '//*[@class="rust fn"]' 'F: FnMut(u8) + Clone'
pub fn f0<F: FnMut(u8) + Clone>(f: F) {}
|
// @has 'foo/fn.f1.html' '//*[@class="rust fn"]' 'F: FnMut(u16) + Clone'
pub fn f1<F: FnMut(u16) -> () + Clone>(f: F) {}
// @has 'foo/fn.f2.html' '//*[@class="rust fn"]' 'F: FnMut(u32) + Clone'
pub use unit_return::f2;
// @has 'foo/fn.f3.html' '//*[@class="rust fn"]' 'F: FnMut(u64) + Clone'
pub use unit_return::f3;
|
random_line_split
|
|
unit-return.rs
|
// aux-build:unit-return.rs
#![crate_name = "foo"]
extern crate unit_return;
// @has 'foo/fn.f0.html' '//*[@class="rust fn"]' 'F: FnMut(u8) + Clone'
pub fn f0<F: FnMut(u8) + Clone>(f: F)
|
// @has 'foo/fn.f1.html' '//*[@class="rust fn"]' 'F: FnMut(u16) + Clone'
pub fn f1<F: FnMut(u16) -> () + Clone>(f: F) {}
// @has 'foo/fn.f2.html' '//*[@class="rust fn"]' 'F: FnMut(u32) + Clone'
pub use unit_return::f2;
// @has 'foo/fn.f3.html' '//*[@class="rust fn"]' 'F: FnMut(u64) + Clone'
pub use unit_return::f3;
|
{}
|
identifier_body
|
unit-return.rs
|
// aux-build:unit-return.rs
#![crate_name = "foo"]
extern crate unit_return;
// @has 'foo/fn.f0.html' '//*[@class="rust fn"]' 'F: FnMut(u8) + Clone'
pub fn f0<F: FnMut(u8) + Clone>(f: F) {}
// @has 'foo/fn.f1.html' '//*[@class="rust fn"]' 'F: FnMut(u16) + Clone'
pub fn
|
<F: FnMut(u16) -> () + Clone>(f: F) {}
// @has 'foo/fn.f2.html' '//*[@class="rust fn"]' 'F: FnMut(u32) + Clone'
pub use unit_return::f2;
// @has 'foo/fn.f3.html' '//*[@class="rust fn"]' 'F: FnMut(u64) + Clone'
pub use unit_return::f3;
|
f1
|
identifier_name
|
astconv.rs
|
expected {} but found {}",
expected_num_region_params,
supplied_num_region_params));
}
match anon_regions {
Ok(v) => opt_vec::from(v),
Err(()) => opt_vec::from(vec::from_fn(expected_num_region_params,
|_| ty::ReStatic)) // hokey
}
};
// Convert the type parameters supplied by the user.
let supplied_type_parameter_count =
path.segments.iter().flat_map(|s| s.types.iter()).len();
if decl_generics.type_param_defs.len()!= supplied_type_parameter_count {
this.tcx().sess.span_fatal(
path.span,
format!("wrong number of type arguments: expected {} but found {}",
decl_generics.type_param_defs.len(),
supplied_type_parameter_count));
}
let tps = path.segments
.iter()
.flat_map(|s| s.types.iter())
.map(|&a_t| ast_ty_to_ty(this, rscope, a_t))
.collect();
substs {
regions: ty::NonerasedRegions(regions),
self_ty: self_ty,
tps: tps
}
}
pub fn ast_path_to_substs_and_ty<AC:AstConv,
RS:RegionScope>(
this: &AC,
rscope: &RS,
did: ast::DefId,
path: &ast::Path)
-> ty_param_substs_and_ty {
let tcx = this.tcx();
let ty::ty_param_bounds_and_ty {
generics: generics,
ty: decl_ty
} = this.get_item_ty(did);
let substs = ast_path_substs(this, rscope, &generics, None, path);
let ty = ty::subst(tcx, &substs, decl_ty);
ty_param_substs_and_ty { substs: substs, ty: ty }
}
pub fn ast_path_to_trait_ref<AC:AstConv,RS:RegionScope>(
this: &AC,
rscope: &RS,
trait_def_id: ast::DefId,
self_ty: Option<ty::t>,
path: &ast::Path) -> @ty::TraitRef
{
let trait_def =
this.get_trait_def(trait_def_id);
let substs =
ast_path_substs(
this,
rscope,
&trait_def.generics,
self_ty,
path);
let trait_ref =
@ty::TraitRef {def_id: trait_def_id,
substs: substs};
return trait_ref;
}
pub fn ast_path_to_ty<AC:AstConv,RS:RegionScope>(
this: &AC,
rscope: &RS,
did: ast::DefId,
path: &ast::Path)
-> ty_param_substs_and_ty
{
// Look up the polytype of the item and then substitute the provided types
// for any type/region parameters.
let ty::ty_param_substs_and_ty {
substs: substs,
ty: ty
} = ast_path_to_substs_and_ty(this, rscope, did, path);
ty_param_substs_and_ty { substs: substs, ty: ty }
}
pub static NO_REGIONS: uint = 1;
pub static NO_TPS: uint = 2;
// Parses the programmer's textual representation of a type into our
// internal notion of a type.
pub fn ast_ty_to_ty<AC:AstConv, RS:RegionScope>(
this: &AC, rscope: &RS, ast_ty: &ast::Ty) -> ty::t {
fn ast_ty_to_mt<AC:AstConv, RS:RegionScope>(
this: &AC, rscope: &RS, ty: &ast::Ty) -> ty::mt {
ty::mt {ty: ast_ty_to_ty(this, rscope, ty), mutbl: ast::MutImmutable}
}
fn ast_mt_to_mt<AC:AstConv, RS:RegionScope>(
this: &AC, rscope: &RS, mt: &ast::MutTy) -> ty::mt {
ty::mt {ty: ast_ty_to_ty(this, rscope, mt.ty), mutbl: mt.mutbl}
}
// Handle @, ~, and & being able to mean strs and vecs.
// If a_seq_ty is a str or a vec, make it an str/vec.
// Also handle first-class trait types.
fn mk_pointer<AC:AstConv,
RS:RegionScope>(
this: &AC,
rscope: &RS,
a_seq_ty: &ast::MutTy,
vst: ty::vstore,
constr: |ty::mt| -> ty::t)
-> ty::t {
let tcx = this.tcx();
debug!("mk_pointer(vst={:?})", vst);
match a_seq_ty.ty.node {
ast::TyVec(ty) => {
let mut mt = ast_ty_to_mt(this, rscope, ty);
if a_seq_ty.mutbl == ast::MutMutable {
mt = ty::mt { ty: mt.ty, mutbl: a_seq_ty.mutbl };
}
debug!("&[]: vst={:?}", vst);
return ty::mk_vec(tcx, mt, vst);
}
ast::TyPath(ref path, ref bounds, id) => {
// Note that the "bounds must be empty if path is not a trait"
// restriction is enforced in the below case for ty_path, which
// will run after this as long as the path isn't a trait.
let def_map = tcx.def_map.borrow();
match def_map.get().find(&id) {
Some(&ast::DefPrimTy(ast::TyStr)) if a_seq_ty.mutbl == ast::MutImmutable => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
return ty::mk_str(tcx, vst);
}
Some(&ast::DefTrait(trait_def_id)) => {
let result = ast_path_to_trait_ref(
this, rscope, trait_def_id, None, path);
let trait_store = match vst {
ty::vstore_box => ty::BoxTraitStore,
ty::vstore_uniq => ty::UniqTraitStore,
ty::vstore_slice(r) => {
ty::RegionTraitStore(r)
}
ty::vstore_fixed(..) => {
tcx.sess.span_err(
path.span,
"@trait, ~trait or &trait are the only supported \
forms of casting-to-trait");
ty::BoxTraitStore
}
};
let bounds = conv_builtin_bounds(this.tcx(), bounds, trait_store);
return ty::mk_trait(tcx,
result.def_id,
result.substs.clone(),
trait_store,
a_seq_ty.mutbl,
bounds);
}
_ => {}
}
}
_ => {}
}
let seq_ty = ast_mt_to_mt(this, rscope, a_seq_ty);
return constr(seq_ty);
}
fn check_path_args(tcx: ty::ctxt,
path: &ast::Path,
flags: uint) {
if (flags & NO_TPS)!= 0u {
if!path.segments.iter().all(|s| s.types.is_empty()) {
tcx.sess.span_err(
path.span,
"type parameters are not allowed on this type");
}
}
if (flags & NO_REGIONS)!= 0u {
if!path.segments.last().lifetimes.is_empty() {
tcx.sess.span_err(
path.span,
"region parameters are not allowed on this type");
}
}
}
let tcx = this.tcx();
{
let mut ast_ty_to_ty_cache = tcx.ast_ty_to_ty_cache.borrow_mut();
match ast_ty_to_ty_cache.get().find(&ast_ty.id) {
Some(&ty::atttce_resolved(ty)) => return ty,
Some(&ty::atttce_unresolved) => {
tcx.sess.span_fatal(ast_ty.span,
"illegal recursive type; insert an enum \
or struct in the cycle, if this is \
desired");
}
None => { /* go on */ }
}
ast_ty_to_ty_cache.get().insert(ast_ty.id, ty::atttce_unresolved);
}
let typ = match ast_ty.node {
ast::TyNil => ty::mk_nil(),
ast::TyBot => ty::mk_bot(),
ast::TyBox(ty) => {
let mt = ast::MutTy { ty: ty, mutbl: ast::MutImmutable };
mk_pointer(this, rscope, &mt, ty::vstore_box,
|tmt| ty::mk_box(tcx, tmt.ty))
}
ast::TyUniq(ty) => {
let mt = ast::MutTy { ty: ty, mutbl: ast::MutImmutable };
mk_pointer(this, rscope, &mt, ty::vstore_uniq,
|tmt| ty::mk_uniq(tcx, tmt.ty))
}
ast::TyVec(ty) => {
tcx.sess.span_err(ast_ty.span, "bare `[]` is not a type");
// return /something/ so they can at least get more errors
ty::mk_vec(tcx, ast_ty_to_mt(this, rscope, ty), ty::vstore_uniq)
}
ast::TyPtr(ref mt) => {
ty::mk_ptr(tcx, ast_mt_to_mt(this, rscope, mt))
}
ast::TyRptr(ref region, ref mt) => {
let r = opt_ast_region_to_region(this, rscope, ast_ty.span, region);
debug!("ty_rptr r={}", r.repr(this.tcx()));
mk_pointer(this, rscope, mt, ty::vstore_slice(r),
|tmt| ty::mk_rptr(tcx, r, tmt))
}
ast::TyTup(ref fields) => {
let flds = fields.map(|&t| ast_ty_to_ty(this, rscope, t));
ty::mk_tup(tcx, flds)
}
ast::TyBareFn(ref bf) => {
if bf.decl.variadic &&!bf.abis.is_c() {
tcx.sess.span_err(ast_ty.span, "variadic function must have C calling convention");
}
ty::mk_bare_fn(tcx, ty_of_bare_fn(this, ast_ty.id, bf.purity,
bf.abis, bf.decl))
}
ast::TyClosure(ref f) => {
if f.sigil == ast::ManagedSigil {
tcx.sess.span_err(ast_ty.span,
"managed closures are not supported");
}
let bounds = conv_builtin_bounds(this.tcx(), &f.bounds, match f.sigil {
// Use corresponding trait store to figure out default bounds
// if none were specified.
ast::BorrowedSigil => ty::RegionTraitStore(ty::ReEmpty), // dummy region
ast::OwnedSigil => ty::UniqTraitStore,
ast::ManagedSigil => ty::BoxTraitStore,
});
let fn_decl = ty_of_closure(this,
rscope,
ast_ty.id,
f.sigil,
f.purity,
f.onceness,
bounds,
&f.region,
f.decl,
None,
ast_ty.span);
ty::mk_closure(tcx, fn_decl)
}
ast::TyPath(ref path, ref bounds, id) => {
let def_map = tcx.def_map.borrow();
let a_def = match def_map.get().find(&id) {
None => tcx.sess.span_fatal(
ast_ty.span, format!("unbound path {}",
path_to_str(path, tcx.sess.intr()))),
Some(&d) => d
};
// Kind bounds on path types are only supported for traits.
match a_def {
// But don't emit the error if the user meant to do a trait anyway.
ast::DefTrait(..) => { },
_ if bounds.is_some() =>
tcx.sess.span_err(ast_ty.span,
"kind bounds can only be used on trait types"),
_ => { },
}
match a_def {
ast::DefTrait(_) => {
let path_str = path_to_str(path, tcx.sess.intr());
tcx.sess.span_err(
ast_ty.span,
format!("reference to trait `{}` where a type is expected; \
try `@{}`, `~{}`, or `&{}`",
path_str, path_str, path_str, path_str));
ty::mk_err()
}
ast::DefTy(did) | ast::DefStruct(did) => {
ast_path_to_ty(this, rscope, did, path).ty
}
ast::DefPrimTy(nty) => {
match nty {
ast::TyBool => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
ty::mk_bool()
}
ast::TyChar => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
ty::mk_char()
}
ast::TyInt(it) => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
ty::mk_mach_int(it)
}
ast::TyUint(uit) => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
ty::mk_mach_uint(uit)
}
ast::TyFloat(ft) => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
ty::mk_mach_float(ft)
}
ast::TyStr => {
tcx.sess.span_err(ast_ty.span,
"bare `str` is not a type");
// return /something/ so they can at least get more errors
ty::mk_str(tcx, ty::vstore_uniq)
}
}
}
ast::DefTyParam(id, n) => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
ty::mk_param(tcx, n, id)
}
ast::DefSelfTy(id) => {
// n.b.: resolve guarantees that the this type only appears in a
// trait, which we rely upon in various places when creating
// substs
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
let did = ast_util::local_def(id);
ty::mk_self(tcx, did)
}
ast::DefMod(id) => {
tcx.sess.span_fatal(ast_ty.span,
format!("found module name used as a type: {}",
ast_map::node_id_to_str(tcx.items, id.node,
token::get_ident_interner())));
|
}
_ => {
tcx.sess.span_fatal(ast_ty.span,
format!("found value name used as a type: {:?}", a_def));
|
random_line_split
|
|
astconv.rs
|
`.
*/
let tcx = this.tcx();
// If the type is parameterized by the this region, then replace this
// region with the current anon region binding (in other words,
// whatever & would get replaced with).
let expected_num_region_params = decl_generics.region_param_defs.len();
let supplied_num_region_params = path.segments.last().lifetimes.len();
let regions = if expected_num_region_params == supplied_num_region_params {
path.segments.last().lifetimes.map(
|l| ast_region_to_region(this.tcx(), l))
} else {
let anon_regions =
rscope.anon_regions(path.span, expected_num_region_params);
if supplied_num_region_params!= 0 || anon_regions.is_err() {
tcx.sess.span_err(
path.span,
format!("wrong number of lifetime parameters: \
expected {} but found {}",
expected_num_region_params,
supplied_num_region_params));
}
match anon_regions {
Ok(v) => opt_vec::from(v),
Err(()) => opt_vec::from(vec::from_fn(expected_num_region_params,
|_| ty::ReStatic)) // hokey
}
};
// Convert the type parameters supplied by the user.
let supplied_type_parameter_count =
path.segments.iter().flat_map(|s| s.types.iter()).len();
if decl_generics.type_param_defs.len()!= supplied_type_parameter_count {
this.tcx().sess.span_fatal(
path.span,
format!("wrong number of type arguments: expected {} but found {}",
decl_generics.type_param_defs.len(),
supplied_type_parameter_count));
}
let tps = path.segments
.iter()
.flat_map(|s| s.types.iter())
.map(|&a_t| ast_ty_to_ty(this, rscope, a_t))
.collect();
substs {
regions: ty::NonerasedRegions(regions),
self_ty: self_ty,
tps: tps
}
}
pub fn ast_path_to_substs_and_ty<AC:AstConv,
RS:RegionScope>(
this: &AC,
rscope: &RS,
did: ast::DefId,
path: &ast::Path)
-> ty_param_substs_and_ty {
let tcx = this.tcx();
let ty::ty_param_bounds_and_ty {
generics: generics,
ty: decl_ty
} = this.get_item_ty(did);
let substs = ast_path_substs(this, rscope, &generics, None, path);
let ty = ty::subst(tcx, &substs, decl_ty);
ty_param_substs_and_ty { substs: substs, ty: ty }
}
pub fn ast_path_to_trait_ref<AC:AstConv,RS:RegionScope>(
this: &AC,
rscope: &RS,
trait_def_id: ast::DefId,
self_ty: Option<ty::t>,
path: &ast::Path) -> @ty::TraitRef
{
let trait_def =
this.get_trait_def(trait_def_id);
let substs =
ast_path_substs(
this,
rscope,
&trait_def.generics,
self_ty,
path);
let trait_ref =
@ty::TraitRef {def_id: trait_def_id,
substs: substs};
return trait_ref;
}
pub fn ast_path_to_ty<AC:AstConv,RS:RegionScope>(
this: &AC,
rscope: &RS,
did: ast::DefId,
path: &ast::Path)
-> ty_param_substs_and_ty
{
// Look up the polytype of the item and then substitute the provided types
// for any type/region parameters.
let ty::ty_param_substs_and_ty {
substs: substs,
ty: ty
} = ast_path_to_substs_and_ty(this, rscope, did, path);
ty_param_substs_and_ty { substs: substs, ty: ty }
}
pub static NO_REGIONS: uint = 1;
pub static NO_TPS: uint = 2;
// Parses the programmer's textual representation of a type into our
// internal notion of a type.
pub fn ast_ty_to_ty<AC:AstConv, RS:RegionScope>(
this: &AC, rscope: &RS, ast_ty: &ast::Ty) -> ty::t {
fn ast_ty_to_mt<AC:AstConv, RS:RegionScope>(
this: &AC, rscope: &RS, ty: &ast::Ty) -> ty::mt {
ty::mt {ty: ast_ty_to_ty(this, rscope, ty), mutbl: ast::MutImmutable}
}
fn ast_mt_to_mt<AC:AstConv, RS:RegionScope>(
this: &AC, rscope: &RS, mt: &ast::MutTy) -> ty::mt {
ty::mt {ty: ast_ty_to_ty(this, rscope, mt.ty), mutbl: mt.mutbl}
}
// Handle @, ~, and & being able to mean strs and vecs.
// If a_seq_ty is a str or a vec, make it an str/vec.
// Also handle first-class trait types.
fn mk_pointer<AC:AstConv,
RS:RegionScope>(
this: &AC,
rscope: &RS,
a_seq_ty: &ast::MutTy,
vst: ty::vstore,
constr: |ty::mt| -> ty::t)
-> ty::t {
let tcx = this.tcx();
debug!("mk_pointer(vst={:?})", vst);
match a_seq_ty.ty.node {
ast::TyVec(ty) => {
let mut mt = ast_ty_to_mt(this, rscope, ty);
if a_seq_ty.mutbl == ast::MutMutable {
mt = ty::mt { ty: mt.ty, mutbl: a_seq_ty.mutbl };
}
debug!("&[]: vst={:?}", vst);
return ty::mk_vec(tcx, mt, vst);
}
ast::TyPath(ref path, ref bounds, id) => {
// Note that the "bounds must be empty if path is not a trait"
// restriction is enforced in the below case for ty_path, which
// will run after this as long as the path isn't a trait.
let def_map = tcx.def_map.borrow();
match def_map.get().find(&id) {
Some(&ast::DefPrimTy(ast::TyStr)) if a_seq_ty.mutbl == ast::MutImmutable => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
return ty::mk_str(tcx, vst);
}
Some(&ast::DefTrait(trait_def_id)) => {
let result = ast_path_to_trait_ref(
this, rscope, trait_def_id, None, path);
let trait_store = match vst {
ty::vstore_box => ty::BoxTraitStore,
ty::vstore_uniq => ty::UniqTraitStore,
ty::vstore_slice(r) => {
ty::RegionTraitStore(r)
}
ty::vstore_fixed(..) => {
tcx.sess.span_err(
path.span,
"@trait, ~trait or &trait are the only supported \
forms of casting-to-trait");
ty::BoxTraitStore
}
};
let bounds = conv_builtin_bounds(this.tcx(), bounds, trait_store);
return ty::mk_trait(tcx,
result.def_id,
result.substs.clone(),
trait_store,
a_seq_ty.mutbl,
bounds);
}
_ => {}
}
}
_ => {}
}
let seq_ty = ast_mt_to_mt(this, rscope, a_seq_ty);
return constr(seq_ty);
}
fn check_path_args(tcx: ty::ctxt,
path: &ast::Path,
flags: uint) {
if (flags & NO_TPS)!= 0u {
if!path.segments.iter().all(|s| s.types.is_empty()) {
tcx.sess.span_err(
path.span,
"type parameters are not allowed on this type");
}
}
if (flags & NO_REGIONS)!= 0u {
if!path.segments.last().lifetimes.is_empty() {
tcx.sess.span_err(
path.span,
"region parameters are not allowed on this type");
}
}
}
let tcx = this.tcx();
{
let mut ast_ty_to_ty_cache = tcx.ast_ty_to_ty_cache.borrow_mut();
match ast_ty_to_ty_cache.get().find(&ast_ty.id) {
Some(&ty::atttce_resolved(ty)) => return ty,
Some(&ty::atttce_unresolved) => {
tcx.sess.span_fatal(ast_ty.span,
"illegal recursive type; insert an enum \
or struct in the cycle, if this is \
desired");
}
None => { /* go on */ }
}
ast_ty_to_ty_cache.get().insert(ast_ty.id, ty::atttce_unresolved);
}
let typ = match ast_ty.node {
ast::TyNil => ty::mk_nil(),
ast::TyBot => ty::mk_bot(),
ast::TyBox(ty) => {
let mt = ast::MutTy { ty: ty, mutbl: ast::MutImmutable };
mk_pointer(this, rscope, &mt, ty::vstore_box,
|tmt| ty::mk_box(tcx, tmt.ty))
}
ast::TyUniq(ty) => {
let mt = ast::MutTy { ty: ty, mutbl: ast::MutImmutable };
mk_pointer(this, rscope, &mt, ty::vstore_uniq,
|tmt| ty::mk_uniq(tcx, tmt.ty))
}
ast::TyVec(ty) =>
|
ast::TyPtr(ref mt) => {
ty::mk_ptr(tcx, ast_mt_to_mt(this, rscope, mt))
}
ast::TyRptr(ref region, ref mt) => {
let r = opt_ast_region_to_region(this, rscope, ast_ty.span, region);
debug!("ty_rptr r={}", r.repr(this.tcx()));
mk_pointer(this, rscope, mt, ty::vstore_slice(r),
|tmt| ty::mk_rptr(tcx, r, tmt))
}
ast::TyTup(ref fields) => {
let flds = fields.map(|&t| ast_ty_to_ty(this, rscope, t));
ty::mk_tup(tcx, flds)
}
ast::TyBareFn(ref bf) => {
if bf.decl.variadic &&!bf.abis.is_c() {
tcx.sess.span_err(ast_ty.span, "variadic function must have C calling convention");
}
ty::mk_bare_fn(tcx, ty_of_bare_fn(this, ast_ty.id, bf.purity,
bf.abis, bf.decl))
}
ast::TyClosure(ref f) => {
if f.sigil == ast::ManagedSigil {
tcx.sess.span_err(ast_ty.span,
"managed closures are not supported");
}
let bounds = conv_builtin_bounds(this.tcx(), &f.bounds, match f.sigil {
// Use corresponding trait store to figure out default bounds
// if none were specified.
ast::BorrowedSigil => ty::RegionTraitStore(ty::ReEmpty), // dummy region
ast::OwnedSigil => ty::UniqTraitStore,
ast::ManagedSigil => ty::BoxTraitStore,
});
let fn_decl = ty_of_closure(this,
rscope,
ast_ty.id,
f.sigil,
f.purity,
f.onceness,
bounds,
&f.region,
f.decl,
None,
ast_ty.span);
ty::mk_closure(tcx, fn_decl)
}
ast::TyPath(ref path, ref bounds, id) => {
let def_map = tcx.def_map.borrow();
let a_def = match def_map.get().find(&id) {
None => tcx.sess.span_fatal(
ast_ty.span, format!("unbound path {}",
path_to_str(path, tcx.sess.intr()))),
Some(&d) => d
};
// Kind bounds on path types are only supported for traits.
match a_def {
// But don't emit the error if the user meant to do a trait anyway.
ast::DefTrait(..) => { },
_ if bounds.is_some() =>
tcx.sess.span_err(ast_ty.span,
"kind bounds can only be used on trait types"),
_ => { },
}
match a_def {
ast::DefTrait(_) => {
let path_str = path_to_str(path, tcx.sess.intr());
tcx.sess.span_err(
ast_ty.span,
format!("reference to trait `{}` where a type is expected; \
try `@{}`, `~{}`, or `&{}`",
path_str, path_str, path_str, path_str));
ty::mk_err()
}
ast::DefTy(did) | ast::DefStruct(did) => {
ast_path_to_ty(this, rscope, did, path).ty
}
ast::DefPrimTy(nty) => {
match nty {
ast::TyBool => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
ty::mk_bool()
}
ast::TyChar => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
ty::mk_char()
}
ast::TyInt(it) => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
ty::mk_mach_int(it)
}
ast::TyUint(uit) => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
ty::mk_mach_uint(uit)
}
ast::TyFloat(ft) => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
ty::mk_mach_float(ft)
}
ast::TyStr => {
tcx.sess.span_err(ast_ty.span,
"bare `str` is not a type");
// return /something/ so they can at least get more errors
ty::mk_str(tcx, ty::vstore_uniq)
}
}
}
ast::DefTyParam(id, n) => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
ty::mk_param(tcx, n, id)
}
ast::DefSelfTy(id) => {
// n.b.: resolve guarantees that the this type only appears in a
// trait, which we rely upon in various places when creating
// substs
check_path_args(tcx, path, NO_TPS
|
{
tcx.sess.span_err(ast_ty.span, "bare `[]` is not a type");
// return /something/ so they can at least get more errors
ty::mk_vec(tcx, ast_ty_to_mt(this, rscope, ty), ty::vstore_uniq)
}
|
conditional_block
|
astconv.rs
|
`.
*/
let tcx = this.tcx();
// If the type is parameterized by the this region, then replace this
// region with the current anon region binding (in other words,
// whatever & would get replaced with).
let expected_num_region_params = decl_generics.region_param_defs.len();
let supplied_num_region_params = path.segments.last().lifetimes.len();
let regions = if expected_num_region_params == supplied_num_region_params {
path.segments.last().lifetimes.map(
|l| ast_region_to_region(this.tcx(), l))
} else {
let anon_regions =
rscope.anon_regions(path.span, expected_num_region_params);
if supplied_num_region_params!= 0 || anon_regions.is_err() {
tcx.sess.span_err(
path.span,
format!("wrong number of lifetime parameters: \
expected {} but found {}",
expected_num_region_params,
supplied_num_region_params));
}
match anon_regions {
Ok(v) => opt_vec::from(v),
Err(()) => opt_vec::from(vec::from_fn(expected_num_region_params,
|_| ty::ReStatic)) // hokey
}
};
// Convert the type parameters supplied by the user.
let supplied_type_parameter_count =
path.segments.iter().flat_map(|s| s.types.iter()).len();
if decl_generics.type_param_defs.len()!= supplied_type_parameter_count {
this.tcx().sess.span_fatal(
path.span,
format!("wrong number of type arguments: expected {} but found {}",
decl_generics.type_param_defs.len(),
supplied_type_parameter_count));
}
let tps = path.segments
.iter()
.flat_map(|s| s.types.iter())
.map(|&a_t| ast_ty_to_ty(this, rscope, a_t))
.collect();
substs {
regions: ty::NonerasedRegions(regions),
self_ty: self_ty,
tps: tps
}
}
pub fn ast_path_to_substs_and_ty<AC:AstConv,
RS:RegionScope>(
this: &AC,
rscope: &RS,
did: ast::DefId,
path: &ast::Path)
-> ty_param_substs_and_ty {
let tcx = this.tcx();
let ty::ty_param_bounds_and_ty {
generics: generics,
ty: decl_ty
} = this.get_item_ty(did);
let substs = ast_path_substs(this, rscope, &generics, None, path);
let ty = ty::subst(tcx, &substs, decl_ty);
ty_param_substs_and_ty { substs: substs, ty: ty }
}
pub fn ast_path_to_trait_ref<AC:AstConv,RS:RegionScope>(
this: &AC,
rscope: &RS,
trait_def_id: ast::DefId,
self_ty: Option<ty::t>,
path: &ast::Path) -> @ty::TraitRef
{
let trait_def =
this.get_trait_def(trait_def_id);
let substs =
ast_path_substs(
this,
rscope,
&trait_def.generics,
self_ty,
path);
let trait_ref =
@ty::TraitRef {def_id: trait_def_id,
substs: substs};
return trait_ref;
}
pub fn ast_path_to_ty<AC:AstConv,RS:RegionScope>(
this: &AC,
rscope: &RS,
did: ast::DefId,
path: &ast::Path)
-> ty_param_substs_and_ty
{
// Look up the polytype of the item and then substitute the provided types
// for any type/region parameters.
let ty::ty_param_substs_and_ty {
substs: substs,
ty: ty
} = ast_path_to_substs_and_ty(this, rscope, did, path);
ty_param_substs_and_ty { substs: substs, ty: ty }
}
pub static NO_REGIONS: uint = 1;
pub static NO_TPS: uint = 2;
// Parses the programmer's textual representation of a type into our
// internal notion of a type.
pub fn ast_ty_to_ty<AC:AstConv, RS:RegionScope>(
this: &AC, rscope: &RS, ast_ty: &ast::Ty) -> ty::t {
fn ast_ty_to_mt<AC:AstConv, RS:RegionScope>(
this: &AC, rscope: &RS, ty: &ast::Ty) -> ty::mt {
ty::mt {ty: ast_ty_to_ty(this, rscope, ty), mutbl: ast::MutImmutable}
}
fn
|
<AC:AstConv, RS:RegionScope>(
this: &AC, rscope: &RS, mt: &ast::MutTy) -> ty::mt {
ty::mt {ty: ast_ty_to_ty(this, rscope, mt.ty), mutbl: mt.mutbl}
}
// Handle @, ~, and & being able to mean strs and vecs.
// If a_seq_ty is a str or a vec, make it an str/vec.
// Also handle first-class trait types.
fn mk_pointer<AC:AstConv,
RS:RegionScope>(
this: &AC,
rscope: &RS,
a_seq_ty: &ast::MutTy,
vst: ty::vstore,
constr: |ty::mt| -> ty::t)
-> ty::t {
let tcx = this.tcx();
debug!("mk_pointer(vst={:?})", vst);
match a_seq_ty.ty.node {
ast::TyVec(ty) => {
let mut mt = ast_ty_to_mt(this, rscope, ty);
if a_seq_ty.mutbl == ast::MutMutable {
mt = ty::mt { ty: mt.ty, mutbl: a_seq_ty.mutbl };
}
debug!("&[]: vst={:?}", vst);
return ty::mk_vec(tcx, mt, vst);
}
ast::TyPath(ref path, ref bounds, id) => {
// Note that the "bounds must be empty if path is not a trait"
// restriction is enforced in the below case for ty_path, which
// will run after this as long as the path isn't a trait.
let def_map = tcx.def_map.borrow();
match def_map.get().find(&id) {
Some(&ast::DefPrimTy(ast::TyStr)) if a_seq_ty.mutbl == ast::MutImmutable => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
return ty::mk_str(tcx, vst);
}
Some(&ast::DefTrait(trait_def_id)) => {
let result = ast_path_to_trait_ref(
this, rscope, trait_def_id, None, path);
let trait_store = match vst {
ty::vstore_box => ty::BoxTraitStore,
ty::vstore_uniq => ty::UniqTraitStore,
ty::vstore_slice(r) => {
ty::RegionTraitStore(r)
}
ty::vstore_fixed(..) => {
tcx.sess.span_err(
path.span,
"@trait, ~trait or &trait are the only supported \
forms of casting-to-trait");
ty::BoxTraitStore
}
};
let bounds = conv_builtin_bounds(this.tcx(), bounds, trait_store);
return ty::mk_trait(tcx,
result.def_id,
result.substs.clone(),
trait_store,
a_seq_ty.mutbl,
bounds);
}
_ => {}
}
}
_ => {}
}
let seq_ty = ast_mt_to_mt(this, rscope, a_seq_ty);
return constr(seq_ty);
}
fn check_path_args(tcx: ty::ctxt,
path: &ast::Path,
flags: uint) {
if (flags & NO_TPS)!= 0u {
if!path.segments.iter().all(|s| s.types.is_empty()) {
tcx.sess.span_err(
path.span,
"type parameters are not allowed on this type");
}
}
if (flags & NO_REGIONS)!= 0u {
if!path.segments.last().lifetimes.is_empty() {
tcx.sess.span_err(
path.span,
"region parameters are not allowed on this type");
}
}
}
let tcx = this.tcx();
{
let mut ast_ty_to_ty_cache = tcx.ast_ty_to_ty_cache.borrow_mut();
match ast_ty_to_ty_cache.get().find(&ast_ty.id) {
Some(&ty::atttce_resolved(ty)) => return ty,
Some(&ty::atttce_unresolved) => {
tcx.sess.span_fatal(ast_ty.span,
"illegal recursive type; insert an enum \
or struct in the cycle, if this is \
desired");
}
None => { /* go on */ }
}
ast_ty_to_ty_cache.get().insert(ast_ty.id, ty::atttce_unresolved);
}
let typ = match ast_ty.node {
ast::TyNil => ty::mk_nil(),
ast::TyBot => ty::mk_bot(),
ast::TyBox(ty) => {
let mt = ast::MutTy { ty: ty, mutbl: ast::MutImmutable };
mk_pointer(this, rscope, &mt, ty::vstore_box,
|tmt| ty::mk_box(tcx, tmt.ty))
}
ast::TyUniq(ty) => {
let mt = ast::MutTy { ty: ty, mutbl: ast::MutImmutable };
mk_pointer(this, rscope, &mt, ty::vstore_uniq,
|tmt| ty::mk_uniq(tcx, tmt.ty))
}
ast::TyVec(ty) => {
tcx.sess.span_err(ast_ty.span, "bare `[]` is not a type");
// return /something/ so they can at least get more errors
ty::mk_vec(tcx, ast_ty_to_mt(this, rscope, ty), ty::vstore_uniq)
}
ast::TyPtr(ref mt) => {
ty::mk_ptr(tcx, ast_mt_to_mt(this, rscope, mt))
}
ast::TyRptr(ref region, ref mt) => {
let r = opt_ast_region_to_region(this, rscope, ast_ty.span, region);
debug!("ty_rptr r={}", r.repr(this.tcx()));
mk_pointer(this, rscope, mt, ty::vstore_slice(r),
|tmt| ty::mk_rptr(tcx, r, tmt))
}
ast::TyTup(ref fields) => {
let flds = fields.map(|&t| ast_ty_to_ty(this, rscope, t));
ty::mk_tup(tcx, flds)
}
ast::TyBareFn(ref bf) => {
if bf.decl.variadic &&!bf.abis.is_c() {
tcx.sess.span_err(ast_ty.span, "variadic function must have C calling convention");
}
ty::mk_bare_fn(tcx, ty_of_bare_fn(this, ast_ty.id, bf.purity,
bf.abis, bf.decl))
}
ast::TyClosure(ref f) => {
if f.sigil == ast::ManagedSigil {
tcx.sess.span_err(ast_ty.span,
"managed closures are not supported");
}
let bounds = conv_builtin_bounds(this.tcx(), &f.bounds, match f.sigil {
// Use corresponding trait store to figure out default bounds
// if none were specified.
ast::BorrowedSigil => ty::RegionTraitStore(ty::ReEmpty), // dummy region
ast::OwnedSigil => ty::UniqTraitStore,
ast::ManagedSigil => ty::BoxTraitStore,
});
let fn_decl = ty_of_closure(this,
rscope,
ast_ty.id,
f.sigil,
f.purity,
f.onceness,
bounds,
&f.region,
f.decl,
None,
ast_ty.span);
ty::mk_closure(tcx, fn_decl)
}
ast::TyPath(ref path, ref bounds, id) => {
let def_map = tcx.def_map.borrow();
let a_def = match def_map.get().find(&id) {
None => tcx.sess.span_fatal(
ast_ty.span, format!("unbound path {}",
path_to_str(path, tcx.sess.intr()))),
Some(&d) => d
};
// Kind bounds on path types are only supported for traits.
match a_def {
// But don't emit the error if the user meant to do a trait anyway.
ast::DefTrait(..) => { },
_ if bounds.is_some() =>
tcx.sess.span_err(ast_ty.span,
"kind bounds can only be used on trait types"),
_ => { },
}
match a_def {
ast::DefTrait(_) => {
let path_str = path_to_str(path, tcx.sess.intr());
tcx.sess.span_err(
ast_ty.span,
format!("reference to trait `{}` where a type is expected; \
try `@{}`, `~{}`, or `&{}`",
path_str, path_str, path_str, path_str));
ty::mk_err()
}
ast::DefTy(did) | ast::DefStruct(did) => {
ast_path_to_ty(this, rscope, did, path).ty
}
ast::DefPrimTy(nty) => {
match nty {
ast::TyBool => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
ty::mk_bool()
}
ast::TyChar => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
ty::mk_char()
}
ast::TyInt(it) => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
ty::mk_mach_int(it)
}
ast::TyUint(uit) => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
ty::mk_mach_uint(uit)
}
ast::TyFloat(ft) => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
ty::mk_mach_float(ft)
}
ast::TyStr => {
tcx.sess.span_err(ast_ty.span,
"bare `str` is not a type");
// return /something/ so they can at least get more errors
ty::mk_str(tcx, ty::vstore_uniq)
}
}
}
ast::DefTyParam(id, n) => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
ty::mk_param(tcx, n, id)
}
ast::DefSelfTy(id) => {
// n.b.: resolve guarantees that the this type only appears in a
// trait, which we rely upon in various places when creating
// substs
check_path_args(tcx, path, NO_TPS
|
ast_mt_to_mt
|
identifier_name
|
astconv.rs
|
I`.
*/
let tcx = this.tcx();
// If the type is parameterized by the this region, then replace this
// region with the current anon region binding (in other words,
// whatever & would get replaced with).
let expected_num_region_params = decl_generics.region_param_defs.len();
let supplied_num_region_params = path.segments.last().lifetimes.len();
let regions = if expected_num_region_params == supplied_num_region_params {
path.segments.last().lifetimes.map(
|l| ast_region_to_region(this.tcx(), l))
} else {
let anon_regions =
rscope.anon_regions(path.span, expected_num_region_params);
if supplied_num_region_params!= 0 || anon_regions.is_err() {
tcx.sess.span_err(
path.span,
format!("wrong number of lifetime parameters: \
expected {} but found {}",
expected_num_region_params,
supplied_num_region_params));
}
match anon_regions {
Ok(v) => opt_vec::from(v),
Err(()) => opt_vec::from(vec::from_fn(expected_num_region_params,
|_| ty::ReStatic)) // hokey
}
};
// Convert the type parameters supplied by the user.
let supplied_type_parameter_count =
path.segments.iter().flat_map(|s| s.types.iter()).len();
if decl_generics.type_param_defs.len()!= supplied_type_parameter_count {
this.tcx().sess.span_fatal(
path.span,
format!("wrong number of type arguments: expected {} but found {}",
decl_generics.type_param_defs.len(),
supplied_type_parameter_count));
}
let tps = path.segments
.iter()
.flat_map(|s| s.types.iter())
.map(|&a_t| ast_ty_to_ty(this, rscope, a_t))
.collect();
substs {
regions: ty::NonerasedRegions(regions),
self_ty: self_ty,
tps: tps
}
}
pub fn ast_path_to_substs_and_ty<AC:AstConv,
RS:RegionScope>(
this: &AC,
rscope: &RS,
did: ast::DefId,
path: &ast::Path)
-> ty_param_substs_and_ty {
let tcx = this.tcx();
let ty::ty_param_bounds_and_ty {
generics: generics,
ty: decl_ty
} = this.get_item_ty(did);
let substs = ast_path_substs(this, rscope, &generics, None, path);
let ty = ty::subst(tcx, &substs, decl_ty);
ty_param_substs_and_ty { substs: substs, ty: ty }
}
pub fn ast_path_to_trait_ref<AC:AstConv,RS:RegionScope>(
this: &AC,
rscope: &RS,
trait_def_id: ast::DefId,
self_ty: Option<ty::t>,
path: &ast::Path) -> @ty::TraitRef
|
pub fn ast_path_to_ty<AC:AstConv,RS:RegionScope>(
this: &AC,
rscope: &RS,
did: ast::DefId,
path: &ast::Path)
-> ty_param_substs_and_ty
{
// Look up the polytype of the item and then substitute the provided types
// for any type/region parameters.
let ty::ty_param_substs_and_ty {
substs: substs,
ty: ty
} = ast_path_to_substs_and_ty(this, rscope, did, path);
ty_param_substs_and_ty { substs: substs, ty: ty }
}
pub static NO_REGIONS: uint = 1;
pub static NO_TPS: uint = 2;
// Parses the programmer's textual representation of a type into our
// internal notion of a type.
pub fn ast_ty_to_ty<AC:AstConv, RS:RegionScope>(
this: &AC, rscope: &RS, ast_ty: &ast::Ty) -> ty::t {
fn ast_ty_to_mt<AC:AstConv, RS:RegionScope>(
this: &AC, rscope: &RS, ty: &ast::Ty) -> ty::mt {
ty::mt {ty: ast_ty_to_ty(this, rscope, ty), mutbl: ast::MutImmutable}
}
fn ast_mt_to_mt<AC:AstConv, RS:RegionScope>(
this: &AC, rscope: &RS, mt: &ast::MutTy) -> ty::mt {
ty::mt {ty: ast_ty_to_ty(this, rscope, mt.ty), mutbl: mt.mutbl}
}
// Handle @, ~, and & being able to mean strs and vecs.
// If a_seq_ty is a str or a vec, make it an str/vec.
// Also handle first-class trait types.
fn mk_pointer<AC:AstConv,
RS:RegionScope>(
this: &AC,
rscope: &RS,
a_seq_ty: &ast::MutTy,
vst: ty::vstore,
constr: |ty::mt| -> ty::t)
-> ty::t {
let tcx = this.tcx();
debug!("mk_pointer(vst={:?})", vst);
match a_seq_ty.ty.node {
ast::TyVec(ty) => {
let mut mt = ast_ty_to_mt(this, rscope, ty);
if a_seq_ty.mutbl == ast::MutMutable {
mt = ty::mt { ty: mt.ty, mutbl: a_seq_ty.mutbl };
}
debug!("&[]: vst={:?}", vst);
return ty::mk_vec(tcx, mt, vst);
}
ast::TyPath(ref path, ref bounds, id) => {
// Note that the "bounds must be empty if path is not a trait"
// restriction is enforced in the below case for ty_path, which
// will run after this as long as the path isn't a trait.
let def_map = tcx.def_map.borrow();
match def_map.get().find(&id) {
Some(&ast::DefPrimTy(ast::TyStr)) if a_seq_ty.mutbl == ast::MutImmutable => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
return ty::mk_str(tcx, vst);
}
Some(&ast::DefTrait(trait_def_id)) => {
let result = ast_path_to_trait_ref(
this, rscope, trait_def_id, None, path);
let trait_store = match vst {
ty::vstore_box => ty::BoxTraitStore,
ty::vstore_uniq => ty::UniqTraitStore,
ty::vstore_slice(r) => {
ty::RegionTraitStore(r)
}
ty::vstore_fixed(..) => {
tcx.sess.span_err(
path.span,
"@trait, ~trait or &trait are the only supported \
forms of casting-to-trait");
ty::BoxTraitStore
}
};
let bounds = conv_builtin_bounds(this.tcx(), bounds, trait_store);
return ty::mk_trait(tcx,
result.def_id,
result.substs.clone(),
trait_store,
a_seq_ty.mutbl,
bounds);
}
_ => {}
}
}
_ => {}
}
let seq_ty = ast_mt_to_mt(this, rscope, a_seq_ty);
return constr(seq_ty);
}
fn check_path_args(tcx: ty::ctxt,
path: &ast::Path,
flags: uint) {
if (flags & NO_TPS)!= 0u {
if!path.segments.iter().all(|s| s.types.is_empty()) {
tcx.sess.span_err(
path.span,
"type parameters are not allowed on this type");
}
}
if (flags & NO_REGIONS)!= 0u {
if!path.segments.last().lifetimes.is_empty() {
tcx.sess.span_err(
path.span,
"region parameters are not allowed on this type");
}
}
}
let tcx = this.tcx();
{
let mut ast_ty_to_ty_cache = tcx.ast_ty_to_ty_cache.borrow_mut();
match ast_ty_to_ty_cache.get().find(&ast_ty.id) {
Some(&ty::atttce_resolved(ty)) => return ty,
Some(&ty::atttce_unresolved) => {
tcx.sess.span_fatal(ast_ty.span,
"illegal recursive type; insert an enum \
or struct in the cycle, if this is \
desired");
}
None => { /* go on */ }
}
ast_ty_to_ty_cache.get().insert(ast_ty.id, ty::atttce_unresolved);
}
let typ = match ast_ty.node {
ast::TyNil => ty::mk_nil(),
ast::TyBot => ty::mk_bot(),
ast::TyBox(ty) => {
let mt = ast::MutTy { ty: ty, mutbl: ast::MutImmutable };
mk_pointer(this, rscope, &mt, ty::vstore_box,
|tmt| ty::mk_box(tcx, tmt.ty))
}
ast::TyUniq(ty) => {
let mt = ast::MutTy { ty: ty, mutbl: ast::MutImmutable };
mk_pointer(this, rscope, &mt, ty::vstore_uniq,
|tmt| ty::mk_uniq(tcx, tmt.ty))
}
ast::TyVec(ty) => {
tcx.sess.span_err(ast_ty.span, "bare `[]` is not a type");
// return /something/ so they can at least get more errors
ty::mk_vec(tcx, ast_ty_to_mt(this, rscope, ty), ty::vstore_uniq)
}
ast::TyPtr(ref mt) => {
ty::mk_ptr(tcx, ast_mt_to_mt(this, rscope, mt))
}
ast::TyRptr(ref region, ref mt) => {
let r = opt_ast_region_to_region(this, rscope, ast_ty.span, region);
debug!("ty_rptr r={}", r.repr(this.tcx()));
mk_pointer(this, rscope, mt, ty::vstore_slice(r),
|tmt| ty::mk_rptr(tcx, r, tmt))
}
ast::TyTup(ref fields) => {
let flds = fields.map(|&t| ast_ty_to_ty(this, rscope, t));
ty::mk_tup(tcx, flds)
}
ast::TyBareFn(ref bf) => {
if bf.decl.variadic &&!bf.abis.is_c() {
tcx.sess.span_err(ast_ty.span, "variadic function must have C calling convention");
}
ty::mk_bare_fn(tcx, ty_of_bare_fn(this, ast_ty.id, bf.purity,
bf.abis, bf.decl))
}
ast::TyClosure(ref f) => {
if f.sigil == ast::ManagedSigil {
tcx.sess.span_err(ast_ty.span,
"managed closures are not supported");
}
let bounds = conv_builtin_bounds(this.tcx(), &f.bounds, match f.sigil {
// Use corresponding trait store to figure out default bounds
// if none were specified.
ast::BorrowedSigil => ty::RegionTraitStore(ty::ReEmpty), // dummy region
ast::OwnedSigil => ty::UniqTraitStore,
ast::ManagedSigil => ty::BoxTraitStore,
});
let fn_decl = ty_of_closure(this,
rscope,
ast_ty.id,
f.sigil,
f.purity,
f.onceness,
bounds,
&f.region,
f.decl,
None,
ast_ty.span);
ty::mk_closure(tcx, fn_decl)
}
ast::TyPath(ref path, ref bounds, id) => {
let def_map = tcx.def_map.borrow();
let a_def = match def_map.get().find(&id) {
None => tcx.sess.span_fatal(
ast_ty.span, format!("unbound path {}",
path_to_str(path, tcx.sess.intr()))),
Some(&d) => d
};
// Kind bounds on path types are only supported for traits.
match a_def {
// But don't emit the error if the user meant to do a trait anyway.
ast::DefTrait(..) => { },
_ if bounds.is_some() =>
tcx.sess.span_err(ast_ty.span,
"kind bounds can only be used on trait types"),
_ => { },
}
match a_def {
ast::DefTrait(_) => {
let path_str = path_to_str(path, tcx.sess.intr());
tcx.sess.span_err(
ast_ty.span,
format!("reference to trait `{}` where a type is expected; \
try `@{}`, `~{}`, or `&{}`",
path_str, path_str, path_str, path_str));
ty::mk_err()
}
ast::DefTy(did) | ast::DefStruct(did) => {
ast_path_to_ty(this, rscope, did, path).ty
}
ast::DefPrimTy(nty) => {
match nty {
ast::TyBool => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
ty::mk_bool()
}
ast::TyChar => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
ty::mk_char()
}
ast::TyInt(it) => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
ty::mk_mach_int(it)
}
ast::TyUint(uit) => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
ty::mk_mach_uint(uit)
}
ast::TyFloat(ft) => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
ty::mk_mach_float(ft)
}
ast::TyStr => {
tcx.sess.span_err(ast_ty.span,
"bare `str` is not a type");
// return /something/ so they can at least get more errors
ty::mk_str(tcx, ty::vstore_uniq)
}
}
}
ast::DefTyParam(id, n) => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
ty::mk_param(tcx, n, id)
}
ast::DefSelfTy(id) => {
// n.b.: resolve guarantees that the this type only appears in a
// trait, which we rely upon in various places when creating
// substs
check_path_args(tcx, path, NO_TPS
|
{
let trait_def =
this.get_trait_def(trait_def_id);
let substs =
ast_path_substs(
this,
rscope,
&trait_def.generics,
self_ty,
path);
let trait_ref =
@ty::TraitRef {def_id: trait_def_id,
substs: substs};
return trait_ref;
}
|
identifier_body
|
animation.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! CSS transitions and animations.
use flow::{self, Flow};
use incremental::{self, RestyleDamage};
use clock_ticks;
use gfx::display_list::OpaqueNode;
use layout_task::{LayoutTask, LayoutTaskData};
use msg::constellation_msg::{AnimationState, Msg, PipelineId};
use script::layout_interface::Animation;
use script_traits::{ConstellationControlMsg, ScriptControlChan};
use std::mem;
use std::sync::mpsc::Sender;
use style::animation::{GetMod, PropertyAnimation};
use style::properties::ComputedValues;
/// Inserts transitions into the queue of running animations as applicable for the given style
/// difference. This is called from the layout worker threads.
pub fn start_transitions_if_applicable(new_animations_sender: &Sender<Animation>,
node: OpaqueNode,
old_style: &ComputedValues,
new_style: &mut ComputedValues) {
for i in 0..new_style.get_animation().transition_property.0.len() {
// Create any property animations, if applicable.
let property_animations = PropertyAnimation::from_transition(i, old_style, new_style);
for property_animation in property_animations.into_iter() {
// Set the property to the initial value.
property_animation.update(new_style, 0.0);
// Kick off the animation.
let now = clock_ticks::precise_time_s() as f32;
let animation_style = new_style.get_animation();
let start_time = now + animation_style.transition_delay.0.get_mod(i).seconds();
new_animations_sender.send(Animation {
node: node.id(),
property_animation: property_animation,
start_time: start_time,
end_time: start_time +
animation_style.transition_duration.0.get_mod(i).seconds(),
}).unwrap()
}
}
}
/// Processes any new animations that were discovered after style recalculation.
pub fn process_new_animations(rw_data: &mut LayoutTaskData, pipeline_id: PipelineId) {
while let Ok(animation) = rw_data.new_animations_receiver.try_recv() {
rw_data.running_animations.push(animation)
}
let animation_state;
if rw_data.running_animations.is_empty() {
animation_state = AnimationState::NoAnimationsPresent;
} else {
animation_state = AnimationState::AnimationsPresent;
}
rw_data.constellation_chan
.0
.send(Msg::ChangeRunningAnimationsState(pipeline_id, animation_state))
.unwrap();
}
/// Recalculates style for an animation. This does *not* run with the DOM lock held.
pub fn recalc_style_for_animation(flow: &mut Flow, animation: &Animation)
|
fragment.style = new_style
});
let base = flow::mut_base(flow);
base.restyle_damage.insert(damage);
for kid in base.children.iter_mut() {
recalc_style_for_animation(kid, animation)
}
}
/// Handles animation updates.
pub fn tick_all_animations(layout_task: &LayoutTask, rw_data: &mut LayoutTaskData) {
let running_animations = mem::replace(&mut rw_data.running_animations, Vec::new());
let now = clock_ticks::precise_time_s() as f32;
for running_animation in running_animations.into_iter() {
layout_task.tick_animation(&running_animation, rw_data);
if now < running_animation.end_time {
// Keep running the animation if it hasn't expired.
rw_data.running_animations.push(running_animation)
}
}
let ScriptControlChan(ref chan) = layout_task.script_chan;
chan.send(ConstellationControlMsg::TickAllAnimations(layout_task.id)).unwrap();
}
|
{
#![allow(unsafe_code)] // #6376
let mut damage = RestyleDamage::empty();
flow.mutate_fragments(&mut |fragment| {
if fragment.node.id() != animation.node {
return
}
let now = clock_ticks::precise_time_s() as f32;
let mut progress = (now - animation.start_time) / animation.duration();
if progress > 1.0 {
progress = 1.0
}
if progress <= 0.0 {
return
}
let mut new_style = fragment.style.clone();
animation.property_animation.update(&mut *unsafe { new_style.make_unique() }, progress);
damage.insert(incremental::compute_damage(&Some(fragment.style.clone()), &new_style));
|
identifier_body
|
animation.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! CSS transitions and animations.
use flow::{self, Flow};
use incremental::{self, RestyleDamage};
use clock_ticks;
use gfx::display_list::OpaqueNode;
use layout_task::{LayoutTask, LayoutTaskData};
use msg::constellation_msg::{AnimationState, Msg, PipelineId};
use script::layout_interface::Animation;
use script_traits::{ConstellationControlMsg, ScriptControlChan};
use std::mem;
use std::sync::mpsc::Sender;
use style::animation::{GetMod, PropertyAnimation};
use style::properties::ComputedValues;
/// Inserts transitions into the queue of running animations as applicable for the given style
/// difference. This is called from the layout worker threads.
pub fn start_transitions_if_applicable(new_animations_sender: &Sender<Animation>,
node: OpaqueNode,
old_style: &ComputedValues,
new_style: &mut ComputedValues) {
for i in 0..new_style.get_animation().transition_property.0.len() {
// Create any property animations, if applicable.
let property_animations = PropertyAnimation::from_transition(i, old_style, new_style);
for property_animation in property_animations.into_iter() {
// Set the property to the initial value.
property_animation.update(new_style, 0.0);
// Kick off the animation.
let now = clock_ticks::precise_time_s() as f32;
let animation_style = new_style.get_animation();
let start_time = now + animation_style.transition_delay.0.get_mod(i).seconds();
new_animations_sender.send(Animation {
node: node.id(),
property_animation: property_animation,
start_time: start_time,
end_time: start_time +
animation_style.transition_duration.0.get_mod(i).seconds(),
}).unwrap()
}
}
}
/// Processes any new animations that were discovered after style recalculation.
pub fn process_new_animations(rw_data: &mut LayoutTaskData, pipeline_id: PipelineId) {
while let Ok(animation) = rw_data.new_animations_receiver.try_recv() {
rw_data.running_animations.push(animation)
|
} else {
animation_state = AnimationState::AnimationsPresent;
}
rw_data.constellation_chan
.0
.send(Msg::ChangeRunningAnimationsState(pipeline_id, animation_state))
.unwrap();
}
/// Recalculates style for an animation. This does *not* run with the DOM lock held.
pub fn recalc_style_for_animation(flow: &mut Flow, animation: &Animation) {
#![allow(unsafe_code)] // #6376
let mut damage = RestyleDamage::empty();
flow.mutate_fragments(&mut |fragment| {
if fragment.node.id()!= animation.node {
return
}
let now = clock_ticks::precise_time_s() as f32;
let mut progress = (now - animation.start_time) / animation.duration();
if progress > 1.0 {
progress = 1.0
}
if progress <= 0.0 {
return
}
let mut new_style = fragment.style.clone();
animation.property_animation.update(&mut *unsafe { new_style.make_unique() }, progress);
damage.insert(incremental::compute_damage(&Some(fragment.style.clone()), &new_style));
fragment.style = new_style
});
let base = flow::mut_base(flow);
base.restyle_damage.insert(damage);
for kid in base.children.iter_mut() {
recalc_style_for_animation(kid, animation)
}
}
/// Handles animation updates.
pub fn tick_all_animations(layout_task: &LayoutTask, rw_data: &mut LayoutTaskData) {
let running_animations = mem::replace(&mut rw_data.running_animations, Vec::new());
let now = clock_ticks::precise_time_s() as f32;
for running_animation in running_animations.into_iter() {
layout_task.tick_animation(&running_animation, rw_data);
if now < running_animation.end_time {
// Keep running the animation if it hasn't expired.
rw_data.running_animations.push(running_animation)
}
}
let ScriptControlChan(ref chan) = layout_task.script_chan;
chan.send(ConstellationControlMsg::TickAllAnimations(layout_task.id)).unwrap();
}
|
}
let animation_state;
if rw_data.running_animations.is_empty() {
animation_state = AnimationState::NoAnimationsPresent;
|
random_line_split
|
animation.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! CSS transitions and animations.
use flow::{self, Flow};
use incremental::{self, RestyleDamage};
use clock_ticks;
use gfx::display_list::OpaqueNode;
use layout_task::{LayoutTask, LayoutTaskData};
use msg::constellation_msg::{AnimationState, Msg, PipelineId};
use script::layout_interface::Animation;
use script_traits::{ConstellationControlMsg, ScriptControlChan};
use std::mem;
use std::sync::mpsc::Sender;
use style::animation::{GetMod, PropertyAnimation};
use style::properties::ComputedValues;
/// Inserts transitions into the queue of running animations as applicable for the given style
/// difference. This is called from the layout worker threads.
pub fn
|
(new_animations_sender: &Sender<Animation>,
node: OpaqueNode,
old_style: &ComputedValues,
new_style: &mut ComputedValues) {
for i in 0..new_style.get_animation().transition_property.0.len() {
// Create any property animations, if applicable.
let property_animations = PropertyAnimation::from_transition(i, old_style, new_style);
for property_animation in property_animations.into_iter() {
// Set the property to the initial value.
property_animation.update(new_style, 0.0);
// Kick off the animation.
let now = clock_ticks::precise_time_s() as f32;
let animation_style = new_style.get_animation();
let start_time = now + animation_style.transition_delay.0.get_mod(i).seconds();
new_animations_sender.send(Animation {
node: node.id(),
property_animation: property_animation,
start_time: start_time,
end_time: start_time +
animation_style.transition_duration.0.get_mod(i).seconds(),
}).unwrap()
}
}
}
/// Processes any new animations that were discovered after style recalculation.
pub fn process_new_animations(rw_data: &mut LayoutTaskData, pipeline_id: PipelineId) {
while let Ok(animation) = rw_data.new_animations_receiver.try_recv() {
rw_data.running_animations.push(animation)
}
let animation_state;
if rw_data.running_animations.is_empty() {
animation_state = AnimationState::NoAnimationsPresent;
} else {
animation_state = AnimationState::AnimationsPresent;
}
rw_data.constellation_chan
.0
.send(Msg::ChangeRunningAnimationsState(pipeline_id, animation_state))
.unwrap();
}
/// Recalculates style for an animation. This does *not* run with the DOM lock held.
pub fn recalc_style_for_animation(flow: &mut Flow, animation: &Animation) {
#![allow(unsafe_code)] // #6376
let mut damage = RestyleDamage::empty();
flow.mutate_fragments(&mut |fragment| {
if fragment.node.id()!= animation.node {
return
}
let now = clock_ticks::precise_time_s() as f32;
let mut progress = (now - animation.start_time) / animation.duration();
if progress > 1.0 {
progress = 1.0
}
if progress <= 0.0 {
return
}
let mut new_style = fragment.style.clone();
animation.property_animation.update(&mut *unsafe { new_style.make_unique() }, progress);
damage.insert(incremental::compute_damage(&Some(fragment.style.clone()), &new_style));
fragment.style = new_style
});
let base = flow::mut_base(flow);
base.restyle_damage.insert(damage);
for kid in base.children.iter_mut() {
recalc_style_for_animation(kid, animation)
}
}
/// Handles animation updates.
pub fn tick_all_animations(layout_task: &LayoutTask, rw_data: &mut LayoutTaskData) {
let running_animations = mem::replace(&mut rw_data.running_animations, Vec::new());
let now = clock_ticks::precise_time_s() as f32;
for running_animation in running_animations.into_iter() {
layout_task.tick_animation(&running_animation, rw_data);
if now < running_animation.end_time {
// Keep running the animation if it hasn't expired.
rw_data.running_animations.push(running_animation)
}
}
let ScriptControlChan(ref chan) = layout_task.script_chan;
chan.send(ConstellationControlMsg::TickAllAnimations(layout_task.id)).unwrap();
}
|
start_transitions_if_applicable
|
identifier_name
|
animation.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! CSS transitions and animations.
use flow::{self, Flow};
use incremental::{self, RestyleDamage};
use clock_ticks;
use gfx::display_list::OpaqueNode;
use layout_task::{LayoutTask, LayoutTaskData};
use msg::constellation_msg::{AnimationState, Msg, PipelineId};
use script::layout_interface::Animation;
use script_traits::{ConstellationControlMsg, ScriptControlChan};
use std::mem;
use std::sync::mpsc::Sender;
use style::animation::{GetMod, PropertyAnimation};
use style::properties::ComputedValues;
/// Inserts transitions into the queue of running animations as applicable for the given style
/// difference. This is called from the layout worker threads.
pub fn start_transitions_if_applicable(new_animations_sender: &Sender<Animation>,
node: OpaqueNode,
old_style: &ComputedValues,
new_style: &mut ComputedValues) {
for i in 0..new_style.get_animation().transition_property.0.len() {
// Create any property animations, if applicable.
let property_animations = PropertyAnimation::from_transition(i, old_style, new_style);
for property_animation in property_animations.into_iter() {
// Set the property to the initial value.
property_animation.update(new_style, 0.0);
// Kick off the animation.
let now = clock_ticks::precise_time_s() as f32;
let animation_style = new_style.get_animation();
let start_time = now + animation_style.transition_delay.0.get_mod(i).seconds();
new_animations_sender.send(Animation {
node: node.id(),
property_animation: property_animation,
start_time: start_time,
end_time: start_time +
animation_style.transition_duration.0.get_mod(i).seconds(),
}).unwrap()
}
}
}
/// Processes any new animations that were discovered after style recalculation.
pub fn process_new_animations(rw_data: &mut LayoutTaskData, pipeline_id: PipelineId) {
while let Ok(animation) = rw_data.new_animations_receiver.try_recv() {
rw_data.running_animations.push(animation)
}
let animation_state;
if rw_data.running_animations.is_empty() {
animation_state = AnimationState::NoAnimationsPresent;
} else {
animation_state = AnimationState::AnimationsPresent;
}
rw_data.constellation_chan
.0
.send(Msg::ChangeRunningAnimationsState(pipeline_id, animation_state))
.unwrap();
}
/// Recalculates style for an animation. This does *not* run with the DOM lock held.
pub fn recalc_style_for_animation(flow: &mut Flow, animation: &Animation) {
#![allow(unsafe_code)] // #6376
let mut damage = RestyleDamage::empty();
flow.mutate_fragments(&mut |fragment| {
if fragment.node.id()!= animation.node {
return
}
let now = clock_ticks::precise_time_s() as f32;
let mut progress = (now - animation.start_time) / animation.duration();
if progress > 1.0
|
if progress <= 0.0 {
return
}
let mut new_style = fragment.style.clone();
animation.property_animation.update(&mut *unsafe { new_style.make_unique() }, progress);
damage.insert(incremental::compute_damage(&Some(fragment.style.clone()), &new_style));
fragment.style = new_style
});
let base = flow::mut_base(flow);
base.restyle_damage.insert(damage);
for kid in base.children.iter_mut() {
recalc_style_for_animation(kid, animation)
}
}
/// Handles animation updates.
pub fn tick_all_animations(layout_task: &LayoutTask, rw_data: &mut LayoutTaskData) {
let running_animations = mem::replace(&mut rw_data.running_animations, Vec::new());
let now = clock_ticks::precise_time_s() as f32;
for running_animation in running_animations.into_iter() {
layout_task.tick_animation(&running_animation, rw_data);
if now < running_animation.end_time {
// Keep running the animation if it hasn't expired.
rw_data.running_animations.push(running_animation)
}
}
let ScriptControlChan(ref chan) = layout_task.script_chan;
chan.send(ConstellationControlMsg::TickAllAnimations(layout_task.id)).unwrap();
}
|
{
progress = 1.0
}
|
conditional_block
|
labels.rs
|
use std::fs::File;
use std::io::{Read, Seek, SeekFrom, self};
use std::iter;
use std::ops::{Index, Range};
use std::path::Path;
use byteorder::{BigEndian, ReadBytesExt};
use cast::From as _0;
use linalg::prelude::*;
/// Labels corresponding to a set of images
pub struct Labels {
data: Vec<u8>,
num_classes: u32,
size: u32,
}
impl Labels {
/// Loads a subset of the labels stored in `path`
pub fn load<P>(path: P, subset: Range<u32>) -> io::Result<Labels> where P: AsRef<Path> {
Labels::load_(path.as_ref(), subset)
}
fn load_(path: &Path, Range { start, end }: Range<u32>) -> io::Result<Labels>
|
let num_classes = u32::from_(*buf.iter().max().unwrap_or(&0)) + 1;
Ok(Labels {
data: buf,
num_classes: num_classes,
size: end - start,
})
}
/// Returns the number of classes
pub fn num_classes(&self) -> u32 {
self.num_classes
}
pub fn to_dataset(&self) -> Mat<f64> {
let mut m = Mat::zeros((self.size, self.num_classes));
for (mut r, &label) in m.rows_mut().zip(&self.data) {
r[u32::from_(label)] = 1.;
}
m
}
}
impl Index<u32> for Labels {
type Output = u8;
fn index(&self, i: u32) -> &u8 {
&self.data[usize::from_(i)]
}
}
|
{
/// Magic number expected in the header
const MAGIC: u32 = 2049;
assert!(start < end);
let mut file = try!(File::open(path));
// Parse the header: MAGIC NLABELS
assert_eq!(try!(file.read_u32::<BigEndian>()), MAGIC);
let nlabels = try!(file.read_u32::<BigEndian>());
assert!(end <= nlabels);
let buf_size = usize::from_(end - start);
let mut buf: Vec<_> = iter::repeat(0).take(buf_size).collect();
try!(file.seek(SeekFrom::Current(i64::from_(start))));
assert_eq!(try!(file.read(&mut buf)), buf_size);
|
identifier_body
|
labels.rs
|
use std::fs::File;
use std::io::{Read, Seek, SeekFrom, self};
use std::iter;
use std::ops::{Index, Range};
use std::path::Path;
use byteorder::{BigEndian, ReadBytesExt};
use cast::From as _0;
use linalg::prelude::*;
/// Labels corresponding to a set of images
pub struct Labels {
data: Vec<u8>,
num_classes: u32,
size: u32,
}
impl Labels {
/// Loads a subset of the labels stored in `path`
pub fn load<P>(path: P, subset: Range<u32>) -> io::Result<Labels> where P: AsRef<Path> {
Labels::load_(path.as_ref(), subset)
}
fn load_(path: &Path, Range { start, end }: Range<u32>) -> io::Result<Labels> {
/// Magic number expected in the header
const MAGIC: u32 = 2049;
assert!(start < end);
let mut file = try!(File::open(path));
// Parse the header: MAGIC NLABELS
assert_eq!(try!(file.read_u32::<BigEndian>()), MAGIC);
let nlabels = try!(file.read_u32::<BigEndian>());
assert!(end <= nlabels);
let buf_size = usize::from_(end - start);
let mut buf: Vec<_> = iter::repeat(0).take(buf_size).collect();
try!(file.seek(SeekFrom::Current(i64::from_(start))));
assert_eq!(try!(file.read(&mut buf)), buf_size);
let num_classes = u32::from_(*buf.iter().max().unwrap_or(&0)) + 1;
Ok(Labels {
data: buf,
num_classes: num_classes,
size: end - start,
})
}
/// Returns the number of classes
pub fn num_classes(&self) -> u32 {
self.num_classes
}
pub fn to_dataset(&self) -> Mat<f64> {
let mut m = Mat::zeros((self.size, self.num_classes));
|
for (mut r, &label) in m.rows_mut().zip(&self.data) {
r[u32::from_(label)] = 1.;
}
m
}
}
impl Index<u32> for Labels {
type Output = u8;
fn index(&self, i: u32) -> &u8 {
&self.data[usize::from_(i)]
}
}
|
random_line_split
|
|
labels.rs
|
use std::fs::File;
use std::io::{Read, Seek, SeekFrom, self};
use std::iter;
use std::ops::{Index, Range};
use std::path::Path;
use byteorder::{BigEndian, ReadBytesExt};
use cast::From as _0;
use linalg::prelude::*;
/// Labels corresponding to a set of images
pub struct Labels {
data: Vec<u8>,
num_classes: u32,
size: u32,
}
impl Labels {
/// Loads a subset of the labels stored in `path`
pub fn
|
<P>(path: P, subset: Range<u32>) -> io::Result<Labels> where P: AsRef<Path> {
Labels::load_(path.as_ref(), subset)
}
fn load_(path: &Path, Range { start, end }: Range<u32>) -> io::Result<Labels> {
/// Magic number expected in the header
const MAGIC: u32 = 2049;
assert!(start < end);
let mut file = try!(File::open(path));
// Parse the header: MAGIC NLABELS
assert_eq!(try!(file.read_u32::<BigEndian>()), MAGIC);
let nlabels = try!(file.read_u32::<BigEndian>());
assert!(end <= nlabels);
let buf_size = usize::from_(end - start);
let mut buf: Vec<_> = iter::repeat(0).take(buf_size).collect();
try!(file.seek(SeekFrom::Current(i64::from_(start))));
assert_eq!(try!(file.read(&mut buf)), buf_size);
let num_classes = u32::from_(*buf.iter().max().unwrap_or(&0)) + 1;
Ok(Labels {
data: buf,
num_classes: num_classes,
size: end - start,
})
}
/// Returns the number of classes
pub fn num_classes(&self) -> u32 {
self.num_classes
}
pub fn to_dataset(&self) -> Mat<f64> {
let mut m = Mat::zeros((self.size, self.num_classes));
for (mut r, &label) in m.rows_mut().zip(&self.data) {
r[u32::from_(label)] = 1.;
}
m
}
}
impl Index<u32> for Labels {
type Output = u8;
fn index(&self, i: u32) -> &u8 {
&self.data[usize::from_(i)]
}
}
|
load
|
identifier_name
|
content_length.rs
|
use std::fmt;
use header::{Header, parsing};
/// `Content-Length` header, defined in
/// [RFC7230](http://tools.ietf.org/html/rfc7230#section-3.3.2)
///
/// When a message does not have a `Transfer-Encoding` header field, a
/// Content-Length header field can provide the anticipated size, as a
/// decimal number of octets, for a potential payload body. For messages
/// that do include a payload body, the Content-Length field-value
/// provides the framing information necessary for determining where the
/// body (and message) ends. For messages that do not include a payload
/// body, the Content-Length indicates the size of the selected
/// representation.
///
/// # ABNF
/// ```plain
/// Content-Length = 1*DIGIT
/// ```
///
/// # Example values
|
///
/// let mut headers = Headers::new();
/// headers.set(ContentLength(1024u64));
/// ```
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ContentLength(pub u64);
impl Header for ContentLength {
#[inline]
fn header_name() -> &'static str {
"Content-Length"
}
fn parse_header(raw: &[Vec<u8>]) -> ::Result<ContentLength> {
// If multiple Content-Length headers were sent, everything can still
// be alright if they all contain the same value, and all parse
// correctly. If not, then it's an error.
raw.iter()
.map(::std::ops::Deref::deref)
.map(parsing::from_raw_str)
.fold(None, |prev, x| {
match (prev, x) {
(None, x) => Some(x),
(e@Some(Err(_)), _ ) => e,
(Some(Ok(prev)), Ok(x)) if prev == x => Some(Ok(prev)),
_ => Some(Err(::Error::Header))
}
})
.unwrap_or(Err(::Error::Header))
.map(ContentLength)
}
#[inline]
fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
}
}
impl fmt::Display for ContentLength {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
}
}
__hyper__deref!(ContentLength => u64);
__hyper_generate_header_serialization!(ContentLength);
__hyper__tm!(ContentLength, tests {
// Testcase from RFC
test_header!(test1, vec![b"3495"], Some(HeaderField(3495)));
test_header!(test_invalid, vec![b"34v95"], None);
// Can't use the test_header macro because "5, 5" gets cleaned to "5".
#[test]
fn test_duplicates() {
let parsed = HeaderField::parse_header(&[b"5"[..].into(),
b"5"[..].into()]).unwrap();
assert_eq!(parsed, HeaderField(5));
assert_eq!(format!("{}", parsed), "5");
}
test_header!(test_duplicates_vary, vec![b"5", b"6", b"5"], None);
});
bench_header!(bench, ContentLength, { vec![b"42349984".to_vec()] });
|
/// * `3495`
///
/// # Example
/// ```
/// use hyper::header::{Headers, ContentLength};
|
random_line_split
|
content_length.rs
|
use std::fmt;
use header::{Header, parsing};
/// `Content-Length` header, defined in
/// [RFC7230](http://tools.ietf.org/html/rfc7230#section-3.3.2)
///
/// When a message does not have a `Transfer-Encoding` header field, a
/// Content-Length header field can provide the anticipated size, as a
/// decimal number of octets, for a potential payload body. For messages
/// that do include a payload body, the Content-Length field-value
/// provides the framing information necessary for determining where the
/// body (and message) ends. For messages that do not include a payload
/// body, the Content-Length indicates the size of the selected
/// representation.
///
/// # ABNF
/// ```plain
/// Content-Length = 1*DIGIT
/// ```
///
/// # Example values
/// * `3495`
///
/// # Example
/// ```
/// use hyper::header::{Headers, ContentLength};
///
/// let mut headers = Headers::new();
/// headers.set(ContentLength(1024u64));
/// ```
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ContentLength(pub u64);
impl Header for ContentLength {
#[inline]
fn
|
() -> &'static str {
"Content-Length"
}
fn parse_header(raw: &[Vec<u8>]) -> ::Result<ContentLength> {
// If multiple Content-Length headers were sent, everything can still
// be alright if they all contain the same value, and all parse
// correctly. If not, then it's an error.
raw.iter()
.map(::std::ops::Deref::deref)
.map(parsing::from_raw_str)
.fold(None, |prev, x| {
match (prev, x) {
(None, x) => Some(x),
(e@Some(Err(_)), _ ) => e,
(Some(Ok(prev)), Ok(x)) if prev == x => Some(Ok(prev)),
_ => Some(Err(::Error::Header))
}
})
.unwrap_or(Err(::Error::Header))
.map(ContentLength)
}
#[inline]
fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
}
}
impl fmt::Display for ContentLength {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
}
}
__hyper__deref!(ContentLength => u64);
__hyper_generate_header_serialization!(ContentLength);
__hyper__tm!(ContentLength, tests {
// Testcase from RFC
test_header!(test1, vec![b"3495"], Some(HeaderField(3495)));
test_header!(test_invalid, vec![b"34v95"], None);
// Can't use the test_header macro because "5, 5" gets cleaned to "5".
#[test]
fn test_duplicates() {
let parsed = HeaderField::parse_header(&[b"5"[..].into(),
b"5"[..].into()]).unwrap();
assert_eq!(parsed, HeaderField(5));
assert_eq!(format!("{}", parsed), "5");
}
test_header!(test_duplicates_vary, vec![b"5", b"6", b"5"], None);
});
bench_header!(bench, ContentLength, { vec![b"42349984".to_vec()] });
|
header_name
|
identifier_name
|
content_length.rs
|
use std::fmt;
use header::{Header, parsing};
/// `Content-Length` header, defined in
/// [RFC7230](http://tools.ietf.org/html/rfc7230#section-3.3.2)
///
/// When a message does not have a `Transfer-Encoding` header field, a
/// Content-Length header field can provide the anticipated size, as a
/// decimal number of octets, for a potential payload body. For messages
/// that do include a payload body, the Content-Length field-value
/// provides the framing information necessary for determining where the
/// body (and message) ends. For messages that do not include a payload
/// body, the Content-Length indicates the size of the selected
/// representation.
///
/// # ABNF
/// ```plain
/// Content-Length = 1*DIGIT
/// ```
///
/// # Example values
/// * `3495`
///
/// # Example
/// ```
/// use hyper::header::{Headers, ContentLength};
///
/// let mut headers = Headers::new();
/// headers.set(ContentLength(1024u64));
/// ```
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ContentLength(pub u64);
impl Header for ContentLength {
#[inline]
fn header_name() -> &'static str {
"Content-Length"
}
fn parse_header(raw: &[Vec<u8>]) -> ::Result<ContentLength> {
// If multiple Content-Length headers were sent, everything can still
// be alright if they all contain the same value, and all parse
// correctly. If not, then it's an error.
raw.iter()
.map(::std::ops::Deref::deref)
.map(parsing::from_raw_str)
.fold(None, |prev, x| {
match (prev, x) {
(None, x) => Some(x),
(e@Some(Err(_)), _ ) => e,
(Some(Ok(prev)), Ok(x)) if prev == x => Some(Ok(prev)),
_ => Some(Err(::Error::Header))
}
})
.unwrap_or(Err(::Error::Header))
.map(ContentLength)
}
#[inline]
fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result
|
}
impl fmt::Display for ContentLength {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
}
}
__hyper__deref!(ContentLength => u64);
__hyper_generate_header_serialization!(ContentLength);
__hyper__tm!(ContentLength, tests {
// Testcase from RFC
test_header!(test1, vec![b"3495"], Some(HeaderField(3495)));
test_header!(test_invalid, vec![b"34v95"], None);
// Can't use the test_header macro because "5, 5" gets cleaned to "5".
#[test]
fn test_duplicates() {
let parsed = HeaderField::parse_header(&[b"5"[..].into(),
b"5"[..].into()]).unwrap();
assert_eq!(parsed, HeaderField(5));
assert_eq!(format!("{}", parsed), "5");
}
test_header!(test_duplicates_vary, vec![b"5", b"6", b"5"], None);
});
bench_header!(bench, ContentLength, { vec![b"42349984".to_vec()] });
|
{
fmt::Display::fmt(&self.0, f)
}
|
identifier_body
|
router.rs
|
use std::fmt;
use std::error::Error;
use std::fmt::Display;
use std::io::Read;
use std::io;
use tiny_http::{Request, Method, StatusCode};
use rustc_serialize::json;
use rustc_serialize::json::Json;
use url_parser;
use url_parser::UrlResource;
use std::io::Cursor;
use tiny_http::Response;
use api;
use context::Context;
use http::{ok, http_response};
pub fn handle_request_and_send_response(context: &mut Context, mut request: Request) -> Result<(), io::Error> {
let response = handle_request(context, &mut request);
request.respond(response)
}
pub fn handle_request(context: &mut Context, mut request: &mut Request) -> Response<Cursor<Vec<u8>>> {
match create_response(context, request) {
Err(RequestError::UnsupportedMethod) => http_response(StatusCode(405), "Method not allowed"),
Err(RequestError::UnknownResource) => http_response(StatusCode(404), format!("Url does not exist")),
Err(RequestError::JsonParseError(err)) => http_response(StatusCode(400), format!("Bad Json: {}", err)),
Err(RequestError::UrlParseError(url)) => http_response(StatusCode(400), format!("Bad Url: {}", url)),
Err(RequestError::ReadError(err)) => http_response(StatusCode(400), format!("Bad Read: {}", err)),
Ok(response) => response,
}
}
/*
Hermes API:
Post /table
{name: name,...}
- Create a table with name <name>
Post /table/<name>/key
{data}
- Create a key in table with name <name> with value <data>
- 400 if table doesn't exist
- 400 if key already exists
PUt /table/<name>/key
{data}
- Update a key in table with name <name> with value <data>
- 400 if table doesn't exist
- 400 if key doesn't exist
Get /table/<name>/<key>
- Return the data for a given key
- 400 if table doesn't exist
- 400 if key doesn't exist
*/
pub fn create_response(context: &mut Context, mut request: &mut Request) -> Result<Response<Cursor<Vec<u8>>>, RequestError> {
let url = try!(get_url(request));
match (request.method().clone(), &url.location[..]) {
(Method::Post, [ref table]) => Ok(api::post_table(&mut context.tables, table)),
(Method::Get, [ref table, ref key]) => Ok(api::get_key(&mut context.tables, table, key)),
(Method::Post, [ref table, ref key]) => {
let json = try!(get_body_as_json(&mut request));
Ok(api::post_key_to_table(&mut context.tables, table, key, json))
},
(Method::Delete, [ref table]) => Ok(api::delete_table(&mut context.tables, table)),
(Method::Delete, [ref table, ref key]) => Ok(api::delete_key_from_table(&mut context.tables, table, key)),
(method, location) => Err(RequestError::UnknownResource),
}
}
#[test]
fn
|
() {
let response = request_router(&Method::Post, UrlResource::from_resource("/foo").unwrap());
assert!(http::response_string(response) == http::response_string(ok("foobar")));
}
#[test]
fn test_vector_match() {
let v = vec!("foo", "bar", "baz");
match ("fish", &v[..]) {
(_, []) => assert!(false),
(_, [elem]) => assert!(false),
("fish", [x, y, z]) => assert!(true),
_ => assert!(false),
}
}
#[derive(Debug)]
pub enum RequestError {
ReadError(io::Error),
UrlParseError(url_parser::UrlParseError),
JsonParseError(json::ParserError),
UnknownResource,
UnsupportedMethod
}
impl fmt::Display for RequestError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
RequestError::ReadError(ref err) => err.fmt(f),
RequestError::UrlParseError(ref err) => err.fmt(f),
RequestError::JsonParseError(ref err) => err.fmt(f),
RequestError::UnknownResource => write!(f, "Unknown Url"), //err.fmt(f),
RequestError::UnsupportedMethod => write!(f, "UnsupportedMethod"),
}
}
}
impl Error for RequestError {
fn description(&self) -> &str {
match *self {
RequestError::ReadError(ref err) => err.description(),
RequestError::JsonParseError(ref err) => err.description(),
RequestError::UrlParseError(ref err) => err.description(),
RequestError::UnknownResource => "Unknown url",
RequestError::UnsupportedMethod => "Unsupported Method",
}
}
}
impl From<io::Error> for RequestError {
fn from(err: io::Error) -> RequestError {
RequestError::ReadError(err)
}
}
impl From<json::ParserError> for RequestError {
fn from(err: json::ParserError) -> RequestError {
RequestError::JsonParseError(err)
}
}
impl From<url_parser::UrlParseError> for RequestError {
fn from(err: url_parser::UrlParseError) -> RequestError {
RequestError::UrlParseError(err)
}
}
/// Attempts to construct a Constructs a new `Rc<T>`.
fn get_body_as_json(request: &mut Request) -> Result<Json, RequestError> {
let mut content = String::new();
try!(request.as_reader().read_to_string(&mut content));
let json: Json = try!(Json::from_str(&content));
Ok(json)
}
fn get_url(request: &Request) -> Result<UrlResource, RequestError> {
Ok(try!(url_parser::parse_url_resource(request.url())))
}
|
test_routing
|
identifier_name
|
router.rs
|
use std::fmt;
use std::error::Error;
use std::fmt::Display;
use std::io::Read;
use std::io;
use tiny_http::{Request, Method, StatusCode};
use rustc_serialize::json;
use rustc_serialize::json::Json;
use url_parser;
use url_parser::UrlResource;
use std::io::Cursor;
use tiny_http::Response;
use api;
use context::Context;
use http::{ok, http_response};
pub fn handle_request_and_send_response(context: &mut Context, mut request: Request) -> Result<(), io::Error> {
let response = handle_request(context, &mut request);
request.respond(response)
}
pub fn handle_request(context: &mut Context, mut request: &mut Request) -> Response<Cursor<Vec<u8>>> {
match create_response(context, request) {
Err(RequestError::UnsupportedMethod) => http_response(StatusCode(405), "Method not allowed"),
Err(RequestError::UnknownResource) => http_response(StatusCode(404), format!("Url does not exist")),
Err(RequestError::JsonParseError(err)) => http_response(StatusCode(400), format!("Bad Json: {}", err)),
Err(RequestError::UrlParseError(url)) => http_response(StatusCode(400), format!("Bad Url: {}", url)),
Err(RequestError::ReadError(err)) => http_response(StatusCode(400), format!("Bad Read: {}", err)),
Ok(response) => response,
}
}
/*
Hermes API:
Post /table
{name: name,...}
- Create a table with name <name>
Post /table/<name>/key
{data}
- Create a key in table with name <name> with value <data>
- 400 if table doesn't exist
- 400 if key already exists
PUt /table/<name>/key
{data}
- Update a key in table with name <name> with value <data>
- 400 if table doesn't exist
- 400 if key doesn't exist
Get /table/<name>/<key>
- Return the data for a given key
- 400 if table doesn't exist
- 400 if key doesn't exist
*/
pub fn create_response(context: &mut Context, mut request: &mut Request) -> Result<Response<Cursor<Vec<u8>>>, RequestError> {
let url = try!(get_url(request));
match (request.method().clone(), &url.location[..]) {
(Method::Post, [ref table]) => Ok(api::post_table(&mut context.tables, table)),
(Method::Get, [ref table, ref key]) => Ok(api::get_key(&mut context.tables, table, key)),
(Method::Post, [ref table, ref key]) => {
let json = try!(get_body_as_json(&mut request));
Ok(api::post_key_to_table(&mut context.tables, table, key, json))
},
(Method::Delete, [ref table]) => Ok(api::delete_table(&mut context.tables, table)),
(Method::Delete, [ref table, ref key]) => Ok(api::delete_key_from_table(&mut context.tables, table, key)),
(method, location) => Err(RequestError::UnknownResource),
}
}
#[test]
fn test_routing() {
let response = request_router(&Method::Post, UrlResource::from_resource("/foo").unwrap());
assert!(http::response_string(response) == http::response_string(ok("foobar")));
}
#[test]
fn test_vector_match() {
let v = vec!("foo", "bar", "baz");
match ("fish", &v[..]) {
(_, []) => assert!(false),
(_, [elem]) => assert!(false),
("fish", [x, y, z]) => assert!(true),
_ => assert!(false),
}
}
#[derive(Debug)]
pub enum RequestError {
ReadError(io::Error),
UrlParseError(url_parser::UrlParseError),
JsonParseError(json::ParserError),
UnknownResource,
UnsupportedMethod
}
impl fmt::Display for RequestError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
RequestError::ReadError(ref err) => err.fmt(f),
RequestError::UrlParseError(ref err) => err.fmt(f),
RequestError::JsonParseError(ref err) => err.fmt(f),
RequestError::UnknownResource => write!(f, "Unknown Url"), //err.fmt(f),
RequestError::UnsupportedMethod => write!(f, "UnsupportedMethod"),
}
}
}
impl Error for RequestError {
fn description(&self) -> &str {
match *self {
RequestError::ReadError(ref err) => err.description(),
RequestError::JsonParseError(ref err) => err.description(),
RequestError::UrlParseError(ref err) => err.description(),
RequestError::UnknownResource => "Unknown url",
RequestError::UnsupportedMethod => "Unsupported Method",
}
}
}
impl From<io::Error> for RequestError {
fn from(err: io::Error) -> RequestError
|
}
impl From<json::ParserError> for RequestError {
fn from(err: json::ParserError) -> RequestError {
RequestError::JsonParseError(err)
}
}
impl From<url_parser::UrlParseError> for RequestError {
fn from(err: url_parser::UrlParseError) -> RequestError {
RequestError::UrlParseError(err)
}
}
/// Attempts to construct a Constructs a new `Rc<T>`.
fn get_body_as_json(request: &mut Request) -> Result<Json, RequestError> {
let mut content = String::new();
try!(request.as_reader().read_to_string(&mut content));
let json: Json = try!(Json::from_str(&content));
Ok(json)
}
fn get_url(request: &Request) -> Result<UrlResource, RequestError> {
Ok(try!(url_parser::parse_url_resource(request.url())))
}
|
{
RequestError::ReadError(err)
}
|
identifier_body
|
router.rs
|
use std::fmt;
use std::error::Error;
use std::fmt::Display;
use std::io::Read;
use std::io;
use tiny_http::{Request, Method, StatusCode};
use rustc_serialize::json;
use rustc_serialize::json::Json;
use url_parser;
use url_parser::UrlResource;
use std::io::Cursor;
use tiny_http::Response;
use api;
use context::Context;
use http::{ok, http_response};
pub fn handle_request_and_send_response(context: &mut Context, mut request: Request) -> Result<(), io::Error> {
let response = handle_request(context, &mut request);
request.respond(response)
}
pub fn handle_request(context: &mut Context, mut request: &mut Request) -> Response<Cursor<Vec<u8>>> {
match create_response(context, request) {
Err(RequestError::UnsupportedMethod) => http_response(StatusCode(405), "Method not allowed"),
Err(RequestError::UnknownResource) => http_response(StatusCode(404), format!("Url does not exist")),
Err(RequestError::JsonParseError(err)) => http_response(StatusCode(400), format!("Bad Json: {}", err)),
Err(RequestError::UrlParseError(url)) => http_response(StatusCode(400), format!("Bad Url: {}", url)),
Err(RequestError::ReadError(err)) => http_response(StatusCode(400), format!("Bad Read: {}", err)),
Ok(response) => response,
}
}
/*
Hermes API:
Post /table
{name: name,...}
- Create a table with name <name>
Post /table/<name>/key
{data}
- Create a key in table with name <name> with value <data>
- 400 if table doesn't exist
- 400 if key already exists
PUt /table/<name>/key
{data}
- Update a key in table with name <name> with value <data>
- 400 if table doesn't exist
- 400 if key doesn't exist
Get /table/<name>/<key>
- Return the data for a given key
- 400 if table doesn't exist
- 400 if key doesn't exist
*/
pub fn create_response(context: &mut Context, mut request: &mut Request) -> Result<Response<Cursor<Vec<u8>>>, RequestError> {
let url = try!(get_url(request));
match (request.method().clone(), &url.location[..]) {
(Method::Post, [ref table]) => Ok(api::post_table(&mut context.tables, table)),
(Method::Get, [ref table, ref key]) => Ok(api::get_key(&mut context.tables, table, key)),
(Method::Post, [ref table, ref key]) => {
let json = try!(get_body_as_json(&mut request));
Ok(api::post_key_to_table(&mut context.tables, table, key, json))
},
(Method::Delete, [ref table]) => Ok(api::delete_table(&mut context.tables, table)),
(Method::Delete, [ref table, ref key]) => Ok(api::delete_key_from_table(&mut context.tables, table, key)),
(method, location) => Err(RequestError::UnknownResource),
}
}
#[test]
fn test_routing() {
let response = request_router(&Method::Post, UrlResource::from_resource("/foo").unwrap());
assert!(http::response_string(response) == http::response_string(ok("foobar")));
}
#[test]
fn test_vector_match() {
let v = vec!("foo", "bar", "baz");
match ("fish", &v[..]) {
(_, []) => assert!(false),
(_, [elem]) => assert!(false),
("fish", [x, y, z]) => assert!(true),
_ => assert!(false),
}
}
#[derive(Debug)]
pub enum RequestError {
ReadError(io::Error),
UrlParseError(url_parser::UrlParseError),
JsonParseError(json::ParserError),
UnknownResource,
UnsupportedMethod
}
impl fmt::Display for RequestError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
RequestError::ReadError(ref err) => err.fmt(f),
RequestError::UrlParseError(ref err) => err.fmt(f),
RequestError::JsonParseError(ref err) => err.fmt(f),
RequestError::UnknownResource => write!(f, "Unknown Url"), //err.fmt(f),
RequestError::UnsupportedMethod => write!(f, "UnsupportedMethod"),
}
}
}
impl Error for RequestError {
fn description(&self) -> &str {
|
RequestError::UrlParseError(ref err) => err.description(),
RequestError::UnknownResource => "Unknown url",
RequestError::UnsupportedMethod => "Unsupported Method",
}
}
}
impl From<io::Error> for RequestError {
fn from(err: io::Error) -> RequestError {
RequestError::ReadError(err)
}
}
impl From<json::ParserError> for RequestError {
fn from(err: json::ParserError) -> RequestError {
RequestError::JsonParseError(err)
}
}
impl From<url_parser::UrlParseError> for RequestError {
fn from(err: url_parser::UrlParseError) -> RequestError {
RequestError::UrlParseError(err)
}
}
/// Attempts to construct a Constructs a new `Rc<T>`.
fn get_body_as_json(request: &mut Request) -> Result<Json, RequestError> {
let mut content = String::new();
try!(request.as_reader().read_to_string(&mut content));
let json: Json = try!(Json::from_str(&content));
Ok(json)
}
fn get_url(request: &Request) -> Result<UrlResource, RequestError> {
Ok(try!(url_parser::parse_url_resource(request.url())))
}
|
match *self {
RequestError::ReadError(ref err) => err.description(),
RequestError::JsonParseError(ref err) => err.description(),
|
random_line_split
|
lib.rs
|
//! This library implements basic processing of JavaScript sourcemaps.
//!
//! # Installation
//!
//! The crate is called sourcemap and you can depend on it via cargo:
//!
//! ```toml
//! [dependencies]
//! sourcemap = "*"
//! ```
//!
//! If you want to use the git version:
//!
//! ```toml
//! [dependencies.sourcemap]
//! git = "https://github.com/getsentry/rust-sourcemap.git"
//! ```
//!
//! # Basic Operation
//!
//! This crate can load JavaScript sourcemaps from JSON files. It uses
//! `serde` for parsing of the JSON data. Due to the nature of sourcemaps
//! the entirety of the file must be loaded into memory which can be quite
//! memory intensive.
//!
//! Usage:
//!
//! ```rust
//! use sourcemap::SourceMap;
//! let input: &[_] = b"{
//! \"version\":3,
|
//! }";
//! let sm = SourceMap::from_reader(input).unwrap();
//! let token = sm.lookup_token(0, 0).unwrap(); // line-number and column
//! println!("token: {}", token);
//! ```
//!
//! # Features
//!
//! Functionality of the crate can be turned on and off by feature flags. This is the
//! current list of feature flags:
//!
//! * `ram_bundle`: turns on RAM bundle support
//!
#[warn(missing_docs)]
mod macros;
pub use crate::builder::SourceMapBuilder;
pub use crate::decoder::{decode, decode_data_url, decode_slice};
pub use crate::detector::{
is_sourcemap, is_sourcemap_slice, locate_sourcemap_reference, locate_sourcemap_reference_slice,
SourceMapRef,
};
pub use crate::errors::{Error, Result};
pub use crate::hermes::SourceMapHermes;
pub use crate::sourceview::SourceView;
pub use crate::types::{
DecodedMap, IndexIter, NameIter, RawToken, RewriteOptions, SourceContentsIter, SourceIter,
SourceMap, SourceMapIndex, SourceMapSection, SourceMapSectionIter, Token, TokenIter,
};
pub use crate::utils::make_relative_path;
mod builder;
mod decoder;
mod detector;
mod encoder;
mod errors;
mod hermes;
mod jsontypes;
mod sourceview;
mod types;
mod utils;
#[cfg(feature = "ram_bundle")]
pub mod ram_bundle;
pub mod vlq;
|
//! \"sources\":[\"coolstuff.js\"],
//! \"names\":[\"x\",\"alert\"],
//! \"mappings\":\"AAAA,GAAIA,GAAI,EACR,IAAIA,GAAK,EAAG,CACVC,MAAM\"
|
random_line_split
|
assign_ops2.rs
|
#[allow(unused_assignments)]
#[warn(clippy::misrefactored_assign_op, clippy::assign_op_pattern)]
fn main() {
let mut a = 5;
a += a + 1;
a += 1 + a;
a -= a - 1;
a *= a * 99;
a *= 42 * a;
a /= a / 2;
a %= a % 5;
a &= a & 1;
a *= a * a;
a = a * a * a;
a = a * 42 * a;
a = a * 2 + a;
a -= 1 - a;
a /= 5 / a;
a %= 42 % a;
a <<= 6 << a;
}
// check that we don't lint on op assign impls, because that's just the way to impl them
use std::ops::{Mul, MulAssign};
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Wrap(i64);
impl Mul<i64> for Wrap {
type Output = Self;
fn mul(self, rhs: i64) -> Self {
Wrap(self.0 * rhs)
}
}
impl MulAssign<i64> for Wrap {
fn mul_assign(&mut self, rhs: i64)
|
}
fn cow_add_assign() {
use std::borrow::Cow;
let mut buf = Cow::Owned(String::from("bar"));
let cows = Cow::Borrowed("foo");
// this can be linted
buf = buf + cows.clone();
// this should not as cow<str> Add is not commutative
buf = cows + buf;
println!("{}", buf);
}
|
{
*self = *self * rhs
}
|
identifier_body
|
assign_ops2.rs
|
#[allow(unused_assignments)]
#[warn(clippy::misrefactored_assign_op, clippy::assign_op_pattern)]
fn main() {
let mut a = 5;
a += a + 1;
a += 1 + a;
a -= a - 1;
a *= a * 99;
a *= 42 * a;
a /= a / 2;
a %= a % 5;
a &= a & 1;
a *= a * a;
a = a * a * a;
a = a * 42 * a;
a = a * 2 + a;
a -= 1 - a;
a /= 5 / a;
a %= 42 % a;
a <<= 6 << a;
}
// check that we don't lint on op assign impls, because that's just the way to impl them
use std::ops::{Mul, MulAssign};
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Wrap(i64);
impl Mul<i64> for Wrap {
type Output = Self;
fn mul(self, rhs: i64) -> Self {
Wrap(self.0 * rhs)
}
}
impl MulAssign<i64> for Wrap {
fn mul_assign(&mut self, rhs: i64) {
*self = *self * rhs
}
}
fn
|
() {
use std::borrow::Cow;
let mut buf = Cow::Owned(String::from("bar"));
let cows = Cow::Borrowed("foo");
// this can be linted
buf = buf + cows.clone();
// this should not as cow<str> Add is not commutative
buf = cows + buf;
println!("{}", buf);
}
|
cow_add_assign
|
identifier_name
|
assign_ops2.rs
|
#[allow(unused_assignments)]
#[warn(clippy::misrefactored_assign_op, clippy::assign_op_pattern)]
fn main() {
let mut a = 5;
a += a + 1;
a += 1 + a;
a -= a - 1;
a *= a * 99;
a *= 42 * a;
a /= a / 2;
a %= a % 5;
a &= a & 1;
a *= a * a;
a = a * a * a;
a = a * 42 * a;
a = a * 2 + a;
a -= 1 - a;
a /= 5 / a;
a %= 42 % a;
a <<= 6 << a;
}
// check that we don't lint on op assign impls, because that's just the way to impl them
use std::ops::{Mul, MulAssign};
|
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Wrap(i64);
impl Mul<i64> for Wrap {
type Output = Self;
fn mul(self, rhs: i64) -> Self {
Wrap(self.0 * rhs)
}
}
impl MulAssign<i64> for Wrap {
fn mul_assign(&mut self, rhs: i64) {
*self = *self * rhs
}
}
fn cow_add_assign() {
use std::borrow::Cow;
let mut buf = Cow::Owned(String::from("bar"));
let cows = Cow::Borrowed("foo");
// this can be linted
buf = buf + cows.clone();
// this should not as cow<str> Add is not commutative
buf = cows + buf;
println!("{}", buf);
}
|
random_line_split
|
|
lib.rs
|
#![allow(non_upper_case_globals)]
#![allow(non_snake_case)]
#![allow(private_no_mangle_fns)]
#![feature(proc_macro)]
#![cfg_attr(feature = "strict", deny(warnings))]
#![feature(global_allocator)]
#![feature(concat_idents)]
#[macro_use]
extern crate lazy_static;
extern crate base64 as base64_crate;
extern crate libc;
extern crate md5;
extern crate rand;
extern crate sha1;
extern crate sha2;
// Wilfred/remacs#38 : Need to override the allocator for legacy unexec support on Mac.
#[cfg(all(not(test), target_os = "macos"))]
extern crate alloc_unexecmacosx;
// Needed for linking.
extern crate remacs_lib;
extern crate remacs_macros;
extern crate remacs_sys;
#[cfg(test)]
extern crate mock_derive;
#[cfg(test)]
#[macro_use]
mod functions;
#[macro_use]
mod eval;
#[macro_use]
mod lisp;
#[macro_use]
mod vector_macros;
mod str2sig;
mod base64;
mod buffers;
mod category;
mod character;
mod chartable;
mod cmds;
mod crypto;
mod data;
mod dispnew;
mod editfns;
mod floatfns;
mod fns;
mod fonts;
mod frames;
mod hashtable;
mod indent;
mod interactive;
mod keyboard;
mod keymap;
mod lists;
mod marker;
mod math;
mod minibuf;
mod multibyte;
mod numbers;
mod obarray;
mod objects;
mod process;
mod strings;
mod symbols;
mod threads;
mod util;
mod vectors;
mod windows;
#[cfg(all(not(test), target_os = "macos"))]
use alloc_unexecmacosx::OsxUnexecAlloc;
#[cfg(all(not(test), target_os = "macos"))]
#[global_allocator]
static ALLOCATOR: OsxUnexecAlloc = OsxUnexecAlloc;
#[no_mangle]
pub extern "C" fn
|
() {
cmds::initial_keys();
}
include!(concat!(env!("OUT_DIR"), "/c_exports.rs"));
#[cfg(test)]
pub use functions::{lispsym, make_string, make_unibyte_string, Fcons, Fsignal};
|
rust_initial_keys
|
identifier_name
|
lib.rs
|
#![allow(non_upper_case_globals)]
#![allow(non_snake_case)]
#![allow(private_no_mangle_fns)]
#![feature(proc_macro)]
#![cfg_attr(feature = "strict", deny(warnings))]
#![feature(global_allocator)]
#![feature(concat_idents)]
#[macro_use]
extern crate lazy_static;
extern crate base64 as base64_crate;
extern crate libc;
extern crate md5;
extern crate rand;
extern crate sha1;
extern crate sha2;
// Wilfred/remacs#38 : Need to override the allocator for legacy unexec support on Mac.
#[cfg(all(not(test), target_os = "macos"))]
extern crate alloc_unexecmacosx;
// Needed for linking.
extern crate remacs_lib;
extern crate remacs_macros;
extern crate remacs_sys;
#[cfg(test)]
extern crate mock_derive;
#[cfg(test)]
#[macro_use]
mod functions;
#[macro_use]
mod eval;
#[macro_use]
mod lisp;
#[macro_use]
mod vector_macros;
mod str2sig;
mod base64;
mod buffers;
mod category;
mod character;
mod chartable;
mod cmds;
mod crypto;
mod data;
mod dispnew;
mod editfns;
mod floatfns;
mod fns;
mod fonts;
mod frames;
|
mod keyboard;
mod keymap;
mod lists;
mod marker;
mod math;
mod minibuf;
mod multibyte;
mod numbers;
mod obarray;
mod objects;
mod process;
mod strings;
mod symbols;
mod threads;
mod util;
mod vectors;
mod windows;
#[cfg(all(not(test), target_os = "macos"))]
use alloc_unexecmacosx::OsxUnexecAlloc;
#[cfg(all(not(test), target_os = "macos"))]
#[global_allocator]
static ALLOCATOR: OsxUnexecAlloc = OsxUnexecAlloc;
#[no_mangle]
pub extern "C" fn rust_initial_keys() {
cmds::initial_keys();
}
include!(concat!(env!("OUT_DIR"), "/c_exports.rs"));
#[cfg(test)]
pub use functions::{lispsym, make_string, make_unibyte_string, Fcons, Fsignal};
|
mod hashtable;
mod indent;
mod interactive;
|
random_line_split
|
lib.rs
|
#![allow(non_upper_case_globals)]
#![allow(non_snake_case)]
#![allow(private_no_mangle_fns)]
#![feature(proc_macro)]
#![cfg_attr(feature = "strict", deny(warnings))]
#![feature(global_allocator)]
#![feature(concat_idents)]
#[macro_use]
extern crate lazy_static;
extern crate base64 as base64_crate;
extern crate libc;
extern crate md5;
extern crate rand;
extern crate sha1;
extern crate sha2;
// Wilfred/remacs#38 : Need to override the allocator for legacy unexec support on Mac.
#[cfg(all(not(test), target_os = "macos"))]
extern crate alloc_unexecmacosx;
// Needed for linking.
extern crate remacs_lib;
extern crate remacs_macros;
extern crate remacs_sys;
#[cfg(test)]
extern crate mock_derive;
#[cfg(test)]
#[macro_use]
mod functions;
#[macro_use]
mod eval;
#[macro_use]
mod lisp;
#[macro_use]
mod vector_macros;
mod str2sig;
mod base64;
mod buffers;
mod category;
mod character;
mod chartable;
mod cmds;
mod crypto;
mod data;
mod dispnew;
mod editfns;
mod floatfns;
mod fns;
mod fonts;
mod frames;
mod hashtable;
mod indent;
mod interactive;
mod keyboard;
mod keymap;
mod lists;
mod marker;
mod math;
mod minibuf;
mod multibyte;
mod numbers;
mod obarray;
mod objects;
mod process;
mod strings;
mod symbols;
mod threads;
mod util;
mod vectors;
mod windows;
#[cfg(all(not(test), target_os = "macos"))]
use alloc_unexecmacosx::OsxUnexecAlloc;
#[cfg(all(not(test), target_os = "macos"))]
#[global_allocator]
static ALLOCATOR: OsxUnexecAlloc = OsxUnexecAlloc;
#[no_mangle]
pub extern "C" fn rust_initial_keys()
|
include!(concat!(env!("OUT_DIR"), "/c_exports.rs"));
#[cfg(test)]
pub use functions::{lispsym, make_string, make_unibyte_string, Fcons, Fsignal};
|
{
cmds::initial_keys();
}
|
identifier_body
|
problem2.rs
|
/// Represents a matrix in row-major order
pub type Matrix = Vec<Vec<f32>>;
/// Computes the product of the inputs `mat1` and `mat2`.
pub fn
|
(mat1: &Matrix, mat2: &Matrix) -> Matrix {
assert!(mat1.len()!= 0 && mat2.len()!= 0);
assert!(mat1[0].len()!= 0 && mat2[0].len()!= 0);
assert_eq!(mat1[0].len(), mat2.len());
println!("{:?}", mat1);
println!("{:?}", mat2);
let mut product = vec![vec![0.; mat2[0].len()]; mat1.len()];
for i in 0..mat1.len() {
for j in 0..mat2[0].len() {
for k in 0..mat1[0].len() {
product[i][j] += mat1[i][k] * mat2[k][j];
}
}
}
println!("{:?}", product);
product
}
|
mat_mult
|
identifier_name
|
problem2.rs
|
/// Represents a matrix in row-major order
pub type Matrix = Vec<Vec<f32>>;
/// Computes the product of the inputs `mat1` and `mat2`.
pub fn mat_mult(mat1: &Matrix, mat2: &Matrix) -> Matrix {
assert!(mat1.len()!= 0 && mat2.len()!= 0);
assert!(mat1[0].len()!= 0 && mat2[0].len()!= 0);
assert_eq!(mat1[0].len(), mat2.len());
println!("{:?}", mat1);
println!("{:?}", mat2);
let mut product = vec![vec![0.; mat2[0].len()]; mat1.len()];
for i in 0..mat1.len() {
for j in 0..mat2[0].len() {
for k in 0..mat1[0].len() {
product[i][j] += mat1[i][k] * mat2[k][j];
}
}
}
println!("{:?}", product);
|
}
|
product
|
random_line_split
|
problem2.rs
|
/// Represents a matrix in row-major order
pub type Matrix = Vec<Vec<f32>>;
/// Computes the product of the inputs `mat1` and `mat2`.
pub fn mat_mult(mat1: &Matrix, mat2: &Matrix) -> Matrix
|
{
assert!(mat1.len() != 0 && mat2.len() != 0);
assert!(mat1[0].len() != 0 && mat2[0].len() != 0);
assert_eq!(mat1[0].len(), mat2.len());
println!("{:?}", mat1);
println!("{:?}", mat2);
let mut product = vec![vec![0.; mat2[0].len()]; mat1.len()];
for i in 0..mat1.len() {
for j in 0..mat2[0].len() {
for k in 0..mat1[0].len() {
product[i][j] += mat1[i][k] * mat2[k][j];
}
}
}
println!("{:?}", product);
product
}
|
identifier_body
|
|
lib.rs
|
// Copyright 2015 Brendan Zabarauskas and the gl-rs developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::os::raw;
pub mod gl {
include!(concat!(env!("OUT_DIR"), "/test_symbols.rs"));
}
|
let _: raw::c_uint = gl::CreateProgram();
gl::CompileShader(5);
gl::GetActiveUniformBlockiv(
0,
0,
gl::UNIFORM_BLOCK_REFERENCED_BY_GEOMETRY_SHADER,
std::ptr::null_mut(),
);
}
}
#[test]
fn test_fallback_works() {
fn loader(name: &str) -> *const raw::c_void {
match name {
"glGenFramebuffers" => 0 as *const raw::c_void,
"glGenFramebuffersEXT" => 42 as *const raw::c_void,
name => panic!("test tried to load {} unexpectedly!", name),
}
};
gl::GenFramebuffers::load_with(loader);
assert!(gl::GenFramebuffers::is_loaded());
}
|
pub fn compile_test_symbols_exist() {
unsafe {
gl::Clear(gl::COLOR_BUFFER_BIT);
|
random_line_split
|
lib.rs
|
// Copyright 2015 Brendan Zabarauskas and the gl-rs developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::os::raw;
pub mod gl {
include!(concat!(env!("OUT_DIR"), "/test_symbols.rs"));
}
pub fn compile_test_symbols_exist() {
unsafe {
gl::Clear(gl::COLOR_BUFFER_BIT);
let _: raw::c_uint = gl::CreateProgram();
gl::CompileShader(5);
gl::GetActiveUniformBlockiv(
0,
0,
gl::UNIFORM_BLOCK_REFERENCED_BY_GEOMETRY_SHADER,
std::ptr::null_mut(),
);
}
}
#[test]
fn test_fallback_works()
|
{
fn loader(name: &str) -> *const raw::c_void {
match name {
"glGenFramebuffers" => 0 as *const raw::c_void,
"glGenFramebuffersEXT" => 42 as *const raw::c_void,
name => panic!("test tried to load {} unexpectedly!", name),
}
};
gl::GenFramebuffers::load_with(loader);
assert!(gl::GenFramebuffers::is_loaded());
}
|
identifier_body
|
|
lib.rs
|
// Copyright 2015 Brendan Zabarauskas and the gl-rs developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::os::raw;
pub mod gl {
include!(concat!(env!("OUT_DIR"), "/test_symbols.rs"));
}
pub fn compile_test_symbols_exist() {
unsafe {
gl::Clear(gl::COLOR_BUFFER_BIT);
let _: raw::c_uint = gl::CreateProgram();
gl::CompileShader(5);
gl::GetActiveUniformBlockiv(
0,
0,
gl::UNIFORM_BLOCK_REFERENCED_BY_GEOMETRY_SHADER,
std::ptr::null_mut(),
);
}
}
#[test]
fn test_fallback_works() {
fn
|
(name: &str) -> *const raw::c_void {
match name {
"glGenFramebuffers" => 0 as *const raw::c_void,
"glGenFramebuffersEXT" => 42 as *const raw::c_void,
name => panic!("test tried to load {} unexpectedly!", name),
}
};
gl::GenFramebuffers::load_with(loader);
assert!(gl::GenFramebuffers::is_loaded());
}
|
loader
|
identifier_name
|
int_macros.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![doc(hidden)]
macro_rules! int_module { ($T:ty, $bits:expr) => (
// FIXME(#11621): Should be deprecated once CTFE is implemented in favour of
// calling the `mem::size_of` function.
#[unstable(feature = "core")]
pub const BITS : u32 = $bits;
// FIXME(#11621): Should be deprecated once CTFE is implemented in favour of
// calling the `mem::size_of` function.
#[unstable(feature = "core")]
pub const BYTES : u32 = ($bits / 8);
// FIXME(#11621): Should be deprecated once CTFE is implemented in favour of
// calling the `Bounded::min_value` function.
|
// calling the `Bounded::max_value` function.
#[stable(feature = "rust1", since = "1.0.0")]
pub const MAX: $T =!MIN;
) }
|
#[stable(feature = "rust1", since = "1.0.0")]
pub const MIN: $T = (-1 as $T) << (BITS - 1);
// FIXME(#9837): Compute MIN like this so the high bits that shouldn't exist are 0.
// FIXME(#11621): Should be deprecated once CTFE is implemented in favour of
|
random_line_split
|
safe.rs
|
// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
//! The `DepGraphSafe` trait
use hir::BodyId;
use hir::def_id::DefId;
use syntax::ast::NodeId;
use ty::TyCtxt;
/// The `DepGraphSafe` trait is used to specify what kinds of values
/// are safe to "leak" into a task. The idea is that this should be
/// only be implemented for things like the tcx as well as various id
/// types, which will create reads in the dep-graph whenever the trait
/// loads anything that might depend on the input program.
pub trait DepGraphSafe {
}
/// A `BodyId` on its own doesn't give access to any particular state.
/// You must fetch the state from the various maps or generate
/// on-demand queries, all of which create reads.
impl DepGraphSafe for BodyId {
}
/// A `NodeId` on its own doesn't give access to any particular state.
/// You must fetch the state from the various maps or generate
/// on-demand queries, all of which create reads.
impl DepGraphSafe for NodeId {
}
/// A `DefId` on its own doesn't give access to any particular state.
/// You must fetch the state from the various maps or generate
/// on-demand queries, all of which create reads.
impl DepGraphSafe for DefId {
}
/// The type context itself can be used to access all kinds of tracked
/// state, but those accesses should always generate read events.
impl<'a, 'gcx, 'tcx> DepGraphSafe for TyCtxt<'a, 'gcx, 'tcx> {
}
/// Tuples make it easy to build up state.
impl<A, B> DepGraphSafe for (A, B)
where A: DepGraphSafe, B: DepGraphSafe
{
}
/// Shared ref to dep-graph-safe stuff should still be dep-graph-safe.
impl<'a, A> DepGraphSafe for &'a A
where A: DepGraphSafe,
{
}
/// Mut ref to dep-graph-safe stuff should still be dep-graph-safe.
impl<'a, A> DepGraphSafe for &'a mut A
where A: DepGraphSafe,
{
}
/// No data here! :)
impl DepGraphSafe for () {
}
/// A convenient override that lets you pass arbitrary state into a
/// task. Every use should be accompanied by a comment explaining why
/// it makes sense (or how it could be refactored away in the future).
pub struct AssertDepGraphSafe<T>(pub T);
impl<T> DepGraphSafe for AssertDepGraphSafe<T> {
}
|
// option. This file may not be copied, modified, or distributed
// except according to those terms.
|
random_line_split
|
safe.rs
|
// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! The `DepGraphSafe` trait
use hir::BodyId;
use hir::def_id::DefId;
use syntax::ast::NodeId;
use ty::TyCtxt;
/// The `DepGraphSafe` trait is used to specify what kinds of values
/// are safe to "leak" into a task. The idea is that this should be
/// only be implemented for things like the tcx as well as various id
/// types, which will create reads in the dep-graph whenever the trait
/// loads anything that might depend on the input program.
pub trait DepGraphSafe {
}
/// A `BodyId` on its own doesn't give access to any particular state.
/// You must fetch the state from the various maps or generate
/// on-demand queries, all of which create reads.
impl DepGraphSafe for BodyId {
}
/// A `NodeId` on its own doesn't give access to any particular state.
/// You must fetch the state from the various maps or generate
/// on-demand queries, all of which create reads.
impl DepGraphSafe for NodeId {
}
/// A `DefId` on its own doesn't give access to any particular state.
/// You must fetch the state from the various maps or generate
/// on-demand queries, all of which create reads.
impl DepGraphSafe for DefId {
}
/// The type context itself can be used to access all kinds of tracked
/// state, but those accesses should always generate read events.
impl<'a, 'gcx, 'tcx> DepGraphSafe for TyCtxt<'a, 'gcx, 'tcx> {
}
/// Tuples make it easy to build up state.
impl<A, B> DepGraphSafe for (A, B)
where A: DepGraphSafe, B: DepGraphSafe
{
}
/// Shared ref to dep-graph-safe stuff should still be dep-graph-safe.
impl<'a, A> DepGraphSafe for &'a A
where A: DepGraphSafe,
{
}
/// Mut ref to dep-graph-safe stuff should still be dep-graph-safe.
impl<'a, A> DepGraphSafe for &'a mut A
where A: DepGraphSafe,
{
}
/// No data here! :)
impl DepGraphSafe for () {
}
/// A convenient override that lets you pass arbitrary state into a
/// task. Every use should be accompanied by a comment explaining why
/// it makes sense (or how it could be refactored away in the future).
pub struct
|
<T>(pub T);
impl<T> DepGraphSafe for AssertDepGraphSafe<T> {
}
|
AssertDepGraphSafe
|
identifier_name
|
compressor.rs
|
/*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
|
use snap::read::FrameDecoder;
use snap::write::FrameEncoder;
/// A trait that provides a compression and decompression strategy for this filter.
/// Conversion takes place on a mutable Vec, to ensure the most performant compression or
/// decompression operation can occur.
pub(crate) trait Compressor {
/// Compress the contents of the Vec - overwriting the original content.
fn encode(&self, contents: &mut Vec<u8>) -> io::Result<()>;
/// Decompress the contents of the Vec - overwriting the original content.
fn decode(&self, contents: &mut Vec<u8>) -> io::Result<()>;
}
pub(crate) struct Snappy {}
impl Compressor for Snappy {
fn encode(&self, contents: &mut Vec<u8>) -> io::Result<()> {
let input = std::mem::take(contents);
let mut wtr = FrameEncoder::new(contents);
io::copy(&mut input.as_slice(), &mut wtr)?;
Ok(())
}
fn decode(&self, contents: &mut Vec<u8>) -> io::Result<()> {
let input = std::mem::take(contents);
let mut rdr = FrameDecoder::new(input.as_slice());
io::copy(&mut rdr, contents)?;
Ok(())
}
}
|
* limitations under the License.
*/
use std::io;
|
random_line_split
|
compressor.rs
|
/*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use std::io;
use snap::read::FrameDecoder;
use snap::write::FrameEncoder;
/// A trait that provides a compression and decompression strategy for this filter.
/// Conversion takes place on a mutable Vec, to ensure the most performant compression or
/// decompression operation can occur.
pub(crate) trait Compressor {
/// Compress the contents of the Vec - overwriting the original content.
fn encode(&self, contents: &mut Vec<u8>) -> io::Result<()>;
/// Decompress the contents of the Vec - overwriting the original content.
fn decode(&self, contents: &mut Vec<u8>) -> io::Result<()>;
}
pub(crate) struct Snappy {}
impl Compressor for Snappy {
fn encode(&self, contents: &mut Vec<u8>) -> io::Result<()> {
let input = std::mem::take(contents);
let mut wtr = FrameEncoder::new(contents);
io::copy(&mut input.as_slice(), &mut wtr)?;
Ok(())
}
fn
|
(&self, contents: &mut Vec<u8>) -> io::Result<()> {
let input = std::mem::take(contents);
let mut rdr = FrameDecoder::new(input.as_slice());
io::copy(&mut rdr, contents)?;
Ok(())
}
}
|
decode
|
identifier_name
|
operation.rs
|
#[repr(u32)]
#[derive(Debug, Clone, Copy)]
pub enum
|
{
/**
* The default storage mode. This constant was added in version 2.6.2 for
* the sake of maintaining a default storage mode, eliminating the need
* for simple storage operations to explicitly define operation.
* Behaviorally it is identical to Set
* in that it will make the server unconditionally store the item, whether
* it exists or not.
*/
Upsert = 0,
/**
* Will cause the operation to fail if the key already exists in the
* cluster.
*/
Add = 1,
/**
* Will cause the operation to fail _unless_ the key already exists in the
* cluster.
*/
Replace = 2,
/** Unconditionally store the item in the cluster */
Set = 3,
/**
* Rather than setting the contents of the entire document, take the value
* specified in value and _append_ it to the existing bytes in
* the value.
*/
Append = 4,
/**
* Like Append, but prepends the new value to the existing value.
*/
Prepend = 5
}
|
Operation
|
identifier_name
|
operation.rs
|
#[repr(u32)]
#[derive(Debug, Clone, Copy)]
pub enum Operation {
/**
* The default storage mode. This constant was added in version 2.6.2 for
* the sake of maintaining a default storage mode, eliminating the need
* for simple storage operations to explicitly define operation.
* Behaviorally it is identical to Set
* in that it will make the server unconditionally store the item, whether
* it exists or not.
*/
Upsert = 0,
/**
* Will cause the operation to fail if the key already exists in the
* cluster.
*/
Add = 1,
/**
|
/** Unconditionally store the item in the cluster */
Set = 3,
/**
* Rather than setting the contents of the entire document, take the value
* specified in value and _append_ it to the existing bytes in
* the value.
*/
Append = 4,
/**
* Like Append, but prepends the new value to the existing value.
*/
Prepend = 5
}
|
* Will cause the operation to fail _unless_ the key already exists in the
* cluster.
*/
Replace = 2,
|
random_line_split
|
mod.rs
|
use self::api_request_processor::ApiReply;
use crate::commands::CommandHelpers;
use crate::entity::EntityRef;
use crate::entity::Realm;
use crate::player_output::PlayerOutput;
use crate::sessions::SessionOutput;
mod api_request_processor;
mod entity_create_command;
mod entity_delete_command;
mod entity_list_command;
mod entity_set_command;
mod property_set_command;
pub use entity_create_command::entity_create;
pub use entity_delete_command::entity_delete;
pub use entity_list_command::entity_list;
pub use entity_set_command::entity_set;
pub use property_set_command::property_set;
pub fn wrap_api_request<F>(
f: F,
) -> Box<dyn Fn(&mut Realm, EntityRef, CommandHelpers) -> Vec<PlayerOutput>>
where
F: Fn(&mut Realm, CommandHelpers) -> Result<ApiReply, ApiReply> +'static,
{
Box::new(move |realm, player_ref, helpers| {
let reply = match realm.player(player_ref) {
Some(player) if player.is_admin() => match f(realm, helpers) {
|
let reply = serde_json::to_value(reply).unwrap();
let mut output: Vec<PlayerOutput> = Vec::new();
push_session_output!(output, player_ref, SessionOutput::Json(reply));
output
})
}
|
Ok(reply) => reply,
Err(error) => error,
},
_ => ApiReply::new_error("", 403, "Forbidden"),
};
|
random_line_split
|
mod.rs
|
use self::api_request_processor::ApiReply;
use crate::commands::CommandHelpers;
use crate::entity::EntityRef;
use crate::entity::Realm;
use crate::player_output::PlayerOutput;
use crate::sessions::SessionOutput;
mod api_request_processor;
mod entity_create_command;
mod entity_delete_command;
mod entity_list_command;
mod entity_set_command;
mod property_set_command;
pub use entity_create_command::entity_create;
pub use entity_delete_command::entity_delete;
pub use entity_list_command::entity_list;
pub use entity_set_command::entity_set;
pub use property_set_command::property_set;
pub fn
|
<F>(
f: F,
) -> Box<dyn Fn(&mut Realm, EntityRef, CommandHelpers) -> Vec<PlayerOutput>>
where
F: Fn(&mut Realm, CommandHelpers) -> Result<ApiReply, ApiReply> +'static,
{
Box::new(move |realm, player_ref, helpers| {
let reply = match realm.player(player_ref) {
Some(player) if player.is_admin() => match f(realm, helpers) {
Ok(reply) => reply,
Err(error) => error,
},
_ => ApiReply::new_error("", 403, "Forbidden"),
};
let reply = serde_json::to_value(reply).unwrap();
let mut output: Vec<PlayerOutput> = Vec::new();
push_session_output!(output, player_ref, SessionOutput::Json(reply));
output
})
}
|
wrap_api_request
|
identifier_name
|
mod.rs
|
use self::api_request_processor::ApiReply;
use crate::commands::CommandHelpers;
use crate::entity::EntityRef;
use crate::entity::Realm;
use crate::player_output::PlayerOutput;
use crate::sessions::SessionOutput;
mod api_request_processor;
mod entity_create_command;
mod entity_delete_command;
mod entity_list_command;
mod entity_set_command;
mod property_set_command;
pub use entity_create_command::entity_create;
pub use entity_delete_command::entity_delete;
pub use entity_list_command::entity_list;
pub use entity_set_command::entity_set;
pub use property_set_command::property_set;
pub fn wrap_api_request<F>(
f: F,
) -> Box<dyn Fn(&mut Realm, EntityRef, CommandHelpers) -> Vec<PlayerOutput>>
where
F: Fn(&mut Realm, CommandHelpers) -> Result<ApiReply, ApiReply> +'static,
|
{
Box::new(move |realm, player_ref, helpers| {
let reply = match realm.player(player_ref) {
Some(player) if player.is_admin() => match f(realm, helpers) {
Ok(reply) => reply,
Err(error) => error,
},
_ => ApiReply::new_error("", 403, "Forbidden"),
};
let reply = serde_json::to_value(reply).unwrap();
let mut output: Vec<PlayerOutput> = Vec::new();
push_session_output!(output, player_ref, SessionOutput::Json(reply));
output
})
}
|
identifier_body
|
|
lock_button.rs
|
// This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with rgtk. If not, see <http://www.gnu.org/licenses/>.
//! A container for arranging buttons
use gtk::cast::GTK_LOCKBUTTON;
use gtk::{self, ffi};
use glib::Permission;
use glib::GlibContainer;
/// GtkLockButton — A widget to unlock or lock privileged operations
struct_Widget!(LockButton);
impl LockButton {
pub fn new(permission: &Permission) -> Option<LockButton> {
|
pub fn get_permission(&self) -> Option<Permission> {
let tmp_pointer = unsafe { ffi::gtk_lock_button_get_permission(GTK_LOCKBUTTON(self.pointer)) };
if tmp_pointer.is_null() {
None
} else {
Some(GlibContainer::wrap(tmp_pointer))
}
}
pub fn set_permission(&self, permission: &Permission) {
unsafe { ffi::gtk_lock_button_set_permission(GTK_LOCKBUTTON(self.pointer), permission.unwrap()) }
}
}
impl_drop!(LockButton);
impl_TraitWidget!(LockButton);
impl gtk::ContainerTrait for LockButton {}
impl gtk::ButtonTrait for LockButton {}
impl gtk::ActionableTrait for LockButton {}
impl_widget_events!(LockButton);
impl_button_events!(LockButton);
|
let tmp_pointer = unsafe { ffi::gtk_lock_button_new(permission.unwrap()) };
check_pointer!(tmp_pointer, LockButton)
}
|
identifier_body
|
lock_button.rs
|
// This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with rgtk. If not, see <http://www.gnu.org/licenses/>.
//! A container for arranging buttons
use gtk::cast::GTK_LOCKBUTTON;
use gtk::{self, ffi};
use glib::Permission;
use glib::GlibContainer;
/// GtkLockButton — A widget to unlock or lock privileged operations
struct_Widget!(LockButton);
impl LockButton {
pub fn new(permission: &Permission) -> Option<LockButton> {
let tmp_pointer = unsafe { ffi::gtk_lock_button_new(permission.unwrap()) };
check_pointer!(tmp_pointer, LockButton)
}
pub fn get_permission(&self) -> Option<Permission> {
let tmp_pointer = unsafe { ffi::gtk_lock_button_get_permission(GTK_LOCKBUTTON(self.pointer)) };
if tmp_pointer.is_null() {
None
} else {
|
}
pub fn set_permission(&self, permission: &Permission) {
unsafe { ffi::gtk_lock_button_set_permission(GTK_LOCKBUTTON(self.pointer), permission.unwrap()) }
}
}
impl_drop!(LockButton);
impl_TraitWidget!(LockButton);
impl gtk::ContainerTrait for LockButton {}
impl gtk::ButtonTrait for LockButton {}
impl gtk::ActionableTrait for LockButton {}
impl_widget_events!(LockButton);
impl_button_events!(LockButton);
|
Some(GlibContainer::wrap(tmp_pointer))
}
|
conditional_block
|
lock_button.rs
|
// This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with rgtk. If not, see <http://www.gnu.org/licenses/>.
//! A container for arranging buttons
use gtk::cast::GTK_LOCKBUTTON;
use gtk::{self, ffi};
use glib::Permission;
use glib::GlibContainer;
/// GtkLockButton — A widget to unlock or lock privileged operations
struct_Widget!(LockButton);
impl LockButton {
pub fn new(permission: &Permission) -> Option<LockButton> {
let tmp_pointer = unsafe { ffi::gtk_lock_button_new(permission.unwrap()) };
check_pointer!(tmp_pointer, LockButton)
}
pub fn ge
|
self) -> Option<Permission> {
let tmp_pointer = unsafe { ffi::gtk_lock_button_get_permission(GTK_LOCKBUTTON(self.pointer)) };
if tmp_pointer.is_null() {
None
} else {
Some(GlibContainer::wrap(tmp_pointer))
}
}
pub fn set_permission(&self, permission: &Permission) {
unsafe { ffi::gtk_lock_button_set_permission(GTK_LOCKBUTTON(self.pointer), permission.unwrap()) }
}
}
impl_drop!(LockButton);
impl_TraitWidget!(LockButton);
impl gtk::ContainerTrait for LockButton {}
impl gtk::ButtonTrait for LockButton {}
impl gtk::ActionableTrait for LockButton {}
impl_widget_events!(LockButton);
impl_button_events!(LockButton);
|
t_permission(&
|
identifier_name
|
lock_button.rs
|
// This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
|
//! A container for arranging buttons
use gtk::cast::GTK_LOCKBUTTON;
use gtk::{self, ffi};
use glib::Permission;
use glib::GlibContainer;
/// GtkLockButton — A widget to unlock or lock privileged operations
struct_Widget!(LockButton);
impl LockButton {
pub fn new(permission: &Permission) -> Option<LockButton> {
let tmp_pointer = unsafe { ffi::gtk_lock_button_new(permission.unwrap()) };
check_pointer!(tmp_pointer, LockButton)
}
pub fn get_permission(&self) -> Option<Permission> {
let tmp_pointer = unsafe { ffi::gtk_lock_button_get_permission(GTK_LOCKBUTTON(self.pointer)) };
if tmp_pointer.is_null() {
None
} else {
Some(GlibContainer::wrap(tmp_pointer))
}
}
pub fn set_permission(&self, permission: &Permission) {
unsafe { ffi::gtk_lock_button_set_permission(GTK_LOCKBUTTON(self.pointer), permission.unwrap()) }
}
}
impl_drop!(LockButton);
impl_TraitWidget!(LockButton);
impl gtk::ContainerTrait for LockButton {}
impl gtk::ButtonTrait for LockButton {}
impl gtk::ActionableTrait for LockButton {}
impl_widget_events!(LockButton);
impl_button_events!(LockButton);
|
// You should have received a copy of the GNU Lesser General Public License
// along with rgtk. If not, see <http://www.gnu.org/licenses/>.
|
random_line_split
|
main.rs
|
// Import Crate Module with shapes
use traits_shapes::shapes;
// use traits_shapes::shapes::HasArea;
// Compile and link to the 'hello_world' Crate so its Modules may be used in main.rs
extern crate traits_shapes;
// Traits are defined similar to the 'impl' keyword that is used to call a function
// with method syntax (implementing a'struct')
// 'trait' blocks are similar to the 'impl' block (however only a Type Signature is
// defined Without a Body) and 'impl Trait for Item' is used rather than 'impl Item'
// Rule: Traits must be used in any scope where the Trait method is used.
// Rule: Trait or the type the 'impl' of the trait is being written for must be inside the crate
|
};
let my_square = shapes::Square {
x: 0.0f64,
y: 0.0f64,
side: 1.0f64,
};
// print_area is now Generic and ensures only correct Types are passed in
shapes::print_area(my_circle); // outputs 3.141593
shapes::print_area(my_square); // outputs 1
shapes::print_area(5); // outputs 5
}
|
fn main() {
let my_circle = shapes::Circle {
x: 0.0f64,
y: 0.0f64,
radius: 1.0f64,
|
random_line_split
|
main.rs
|
// Import Crate Module with shapes
use traits_shapes::shapes;
// use traits_shapes::shapes::HasArea;
// Compile and link to the 'hello_world' Crate so its Modules may be used in main.rs
extern crate traits_shapes;
// Traits are defined similar to the 'impl' keyword that is used to call a function
// with method syntax (implementing a'struct')
// 'trait' blocks are similar to the 'impl' block (however only a Type Signature is
// defined Without a Body) and 'impl Trait for Item' is used rather than 'impl Item'
// Rule: Traits must be used in any scope where the Trait method is used.
// Rule: Trait or the type the 'impl' of the trait is being written for must be inside the crate
fn
|
() {
let my_circle = shapes::Circle {
x: 0.0f64,
y: 0.0f64,
radius: 1.0f64,
};
let my_square = shapes::Square {
x: 0.0f64,
y: 0.0f64,
side: 1.0f64,
};
// print_area is now Generic and ensures only correct Types are passed in
shapes::print_area(my_circle); // outputs 3.141593
shapes::print_area(my_square); // outputs 1
shapes::print_area(5); // outputs 5
}
|
main
|
identifier_name
|
main.rs
|
// Import Crate Module with shapes
use traits_shapes::shapes;
// use traits_shapes::shapes::HasArea;
// Compile and link to the 'hello_world' Crate so its Modules may be used in main.rs
extern crate traits_shapes;
// Traits are defined similar to the 'impl' keyword that is used to call a function
// with method syntax (implementing a'struct')
// 'trait' blocks are similar to the 'impl' block (however only a Type Signature is
// defined Without a Body) and 'impl Trait for Item' is used rather than 'impl Item'
// Rule: Traits must be used in any scope where the Trait method is used.
// Rule: Trait or the type the 'impl' of the trait is being written for must be inside the crate
fn main()
|
{
let my_circle = shapes::Circle {
x: 0.0f64,
y: 0.0f64,
radius: 1.0f64,
};
let my_square = shapes::Square {
x: 0.0f64,
y: 0.0f64,
side: 1.0f64,
};
// print_area is now Generic and ensures only correct Types are passed in
shapes::print_area(my_circle); // outputs 3.141593
shapes::print_area(my_square); // outputs 1
shapes::print_area(5); // outputs 5
}
|
identifier_body
|
|
collection.rs
|
use cobalt_config::Frontmatter;
use cobalt_config::SortOrder;
use liquid;
use crate::error::*;
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
pub struct Collection {
pub title: kstring::KString,
pub slug: kstring::KString,
pub description: Option<kstring::KString>,
pub dir: cobalt_config::RelPath,
pub drafts_dir: Option<cobalt_config::RelPath>,
pub order: SortOrder,
pub rss: Option<cobalt_config::RelPath>,
pub jsonfeed: Option<cobalt_config::RelPath>,
pub publish_date_in_filename: bool,
pub default: Frontmatter,
}
impl Collection {
pub fn from_page_config(
config: cobalt_config::PageCollection,
site: &cobalt_config::Site,
common_default: &cobalt_config::Frontmatter,
) -> Result<Self> {
let mut config: cobalt_config::Collection = config.into();
// Use `site` because the pages are effectively the site
config.title = Some(site.title.clone().unwrap_or_else(|| "".into()));
config.description = site.description.clone();
Self::from_config(config, "pages", false, common_default)
}
pub fn from_post_config(
config: cobalt_config::PostCollection,
site: &cobalt_config::Site,
include_drafts: bool,
common_default: &cobalt_config::Frontmatter,
) -> Result<Self> {
let mut config: cobalt_config::Collection = config.into();
// Default with `site` for people quickly bootstrapping a blog, the blog and site are
// effectively equivalent.
if config.title.is_none() {
config.title = Some(site.title.clone().unwrap_or_else(|| "".into()));
}
if config.description.is_none() {
config.description = site.description.clone();
}
Self::from_config(config, "posts", include_drafts, common_default)
}
fn from_config(
config: cobalt_config::Collection,
slug: &str,
include_drafts: bool,
common_default: &cobalt_config::Frontmatter,
) -> Result<Self> {
let cobalt_config::Collection {
title,
description,
dir,
drafts_dir,
order,
rss,
jsonfeed,
default,
publish_date_in_filename,
} = config;
let title = title.ok_or_else(|| failure::err_msg("Collection is missing a `title`"))?;
let slug = kstring::KString::from_ref(slug);
let dir = dir.unwrap_or_else(|| cobalt_config::RelPath::from_unchecked(slug.as_str()));
let drafts_dir = if include_drafts { drafts_dir } else { None };
let default = default.merge(common_default).merge(&Frontmatter {
collection: Some(slug.clone()),
..Default::default()
});
let new = Collection {
title,
slug,
description,
dir,
drafts_dir,
order,
rss,
jsonfeed,
publish_date_in_filename,
default,
};
Ok(new)
}
pub fn
|
(&self) -> liquid::Object {
let mut attributes: liquid::Object = vec![
(
"title".into(),
liquid::model::Value::scalar(self.title.clone()),
),
(
"slug".into(),
liquid::model::Value::scalar(self.slug.clone()),
),
(
"description".into(),
liquid::model::Value::scalar(self.description.clone().unwrap_or_default()),
),
]
.into_iter()
.collect();
if let Some(rss) = self.rss.as_ref() {
attributes.insert(
"rss".into(),
liquid::model::Value::scalar(rss.as_str().to_owned()),
);
}
if let Some(jsonfeed) = self.jsonfeed.as_ref() {
attributes.insert(
"jsonfeed".into(),
liquid::model::Value::scalar(jsonfeed.as_str().to_owned()),
);
}
attributes
}
}
|
attributes
|
identifier_name
|
collection.rs
|
use cobalt_config::Frontmatter;
use cobalt_config::SortOrder;
use liquid;
use crate::error::*;
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
pub struct Collection {
pub title: kstring::KString,
pub slug: kstring::KString,
pub description: Option<kstring::KString>,
pub dir: cobalt_config::RelPath,
pub drafts_dir: Option<cobalt_config::RelPath>,
pub order: SortOrder,
pub rss: Option<cobalt_config::RelPath>,
pub jsonfeed: Option<cobalt_config::RelPath>,
pub publish_date_in_filename: bool,
pub default: Frontmatter,
}
impl Collection {
pub fn from_page_config(
config: cobalt_config::PageCollection,
site: &cobalt_config::Site,
common_default: &cobalt_config::Frontmatter,
) -> Result<Self> {
let mut config: cobalt_config::Collection = config.into();
// Use `site` because the pages are effectively the site
config.title = Some(site.title.clone().unwrap_or_else(|| "".into()));
config.description = site.description.clone();
Self::from_config(config, "pages", false, common_default)
}
pub fn from_post_config(
config: cobalt_config::PostCollection,
site: &cobalt_config::Site,
include_drafts: bool,
common_default: &cobalt_config::Frontmatter,
) -> Result<Self> {
let mut config: cobalt_config::Collection = config.into();
// Default with `site` for people quickly bootstrapping a blog, the blog and site are
// effectively equivalent.
if config.title.is_none() {
config.title = Some(site.title.clone().unwrap_or_else(|| "".into()));
}
if config.description.is_none() {
config.description = site.description.clone();
}
Self::from_config(config, "posts", include_drafts, common_default)
}
fn from_config(
config: cobalt_config::Collection,
slug: &str,
include_drafts: bool,
common_default: &cobalt_config::Frontmatter,
) -> Result<Self> {
let cobalt_config::Collection {
title,
description,
dir,
drafts_dir,
order,
rss,
jsonfeed,
default,
publish_date_in_filename,
} = config;
let title = title.ok_or_else(|| failure::err_msg("Collection is missing a `title`"))?;
let slug = kstring::KString::from_ref(slug);
let dir = dir.unwrap_or_else(|| cobalt_config::RelPath::from_unchecked(slug.as_str()));
let drafts_dir = if include_drafts { drafts_dir } else { None };
let default = default.merge(common_default).merge(&Frontmatter {
collection: Some(slug.clone()),
..Default::default()
});
let new = Collection {
title,
slug,
description,
dir,
drafts_dir,
order,
rss,
jsonfeed,
publish_date_in_filename,
default,
};
Ok(new)
}
pub fn attributes(&self) -> liquid::Object {
let mut attributes: liquid::Object = vec![
(
"title".into(),
liquid::model::Value::scalar(self.title.clone()),
),
(
"slug".into(),
liquid::model::Value::scalar(self.slug.clone()),
),
(
"description".into(),
liquid::model::Value::scalar(self.description.clone().unwrap_or_default()),
),
]
.into_iter()
.collect();
if let Some(rss) = self.rss.as_ref()
|
if let Some(jsonfeed) = self.jsonfeed.as_ref() {
attributes.insert(
"jsonfeed".into(),
liquid::model::Value::scalar(jsonfeed.as_str().to_owned()),
);
}
attributes
}
}
|
{
attributes.insert(
"rss".into(),
liquid::model::Value::scalar(rss.as_str().to_owned()),
);
}
|
conditional_block
|
collection.rs
|
use cobalt_config::Frontmatter;
use cobalt_config::SortOrder;
use liquid;
use crate::error::*;
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
pub struct Collection {
pub title: kstring::KString,
pub slug: kstring::KString,
pub description: Option<kstring::KString>,
pub dir: cobalt_config::RelPath,
pub drafts_dir: Option<cobalt_config::RelPath>,
pub order: SortOrder,
pub rss: Option<cobalt_config::RelPath>,
pub jsonfeed: Option<cobalt_config::RelPath>,
pub publish_date_in_filename: bool,
pub default: Frontmatter,
}
impl Collection {
pub fn from_page_config(
config: cobalt_config::PageCollection,
site: &cobalt_config::Site,
common_default: &cobalt_config::Frontmatter,
) -> Result<Self> {
let mut config: cobalt_config::Collection = config.into();
// Use `site` because the pages are effectively the site
config.title = Some(site.title.clone().unwrap_or_else(|| "".into()));
config.description = site.description.clone();
Self::from_config(config, "pages", false, common_default)
}
pub fn from_post_config(
config: cobalt_config::PostCollection,
site: &cobalt_config::Site,
include_drafts: bool,
common_default: &cobalt_config::Frontmatter,
) -> Result<Self> {
let mut config: cobalt_config::Collection = config.into();
// Default with `site` for people quickly bootstrapping a blog, the blog and site are
// effectively equivalent.
if config.title.is_none() {
config.title = Some(site.title.clone().unwrap_or_else(|| "".into()));
}
if config.description.is_none() {
config.description = site.description.clone();
}
Self::from_config(config, "posts", include_drafts, common_default)
}
fn from_config(
config: cobalt_config::Collection,
slug: &str,
include_drafts: bool,
common_default: &cobalt_config::Frontmatter,
) -> Result<Self> {
let cobalt_config::Collection {
title,
description,
dir,
drafts_dir,
order,
rss,
jsonfeed,
default,
publish_date_in_filename,
} = config;
let title = title.ok_or_else(|| failure::err_msg("Collection is missing a `title`"))?;
let slug = kstring::KString::from_ref(slug);
let dir = dir.unwrap_or_else(|| cobalt_config::RelPath::from_unchecked(slug.as_str()));
let drafts_dir = if include_drafts { drafts_dir } else { None };
let default = default.merge(common_default).merge(&Frontmatter {
collection: Some(slug.clone()),
..Default::default()
});
let new = Collection {
title,
slug,
description,
dir,
drafts_dir,
order,
rss,
jsonfeed,
publish_date_in_filename,
default,
};
Ok(new)
}
pub fn attributes(&self) -> liquid::Object {
let mut attributes: liquid::Object = vec![
(
"title".into(),
liquid::model::Value::scalar(self.title.clone()),
),
(
"slug".into(),
liquid::model::Value::scalar(self.slug.clone()),
),
(
"description".into(),
liquid::model::Value::scalar(self.description.clone().unwrap_or_default()),
),
]
.into_iter()
.collect();
if let Some(rss) = self.rss.as_ref() {
attributes.insert(
|
attributes.insert(
"jsonfeed".into(),
liquid::model::Value::scalar(jsonfeed.as_str().to_owned()),
);
}
attributes
}
}
|
"rss".into(),
liquid::model::Value::scalar(rss.as_str().to_owned()),
);
}
if let Some(jsonfeed) = self.jsonfeed.as_ref() {
|
random_line_split
|
lib.rs
|
// DO NOT EDIT!
// This file was generated automatically from'src/mako/api/lib.rs.mako'
// DO NOT EDIT!
//! This documentation was generated from *AdSense Host* crate version *0.1.8+20150617*, where *20150617* is the exact revision of the *adsensehost:v4.1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.8*.
//!
//! Everything else about the *AdSense Host* *v4d1* API can be found at the
//! [official documentation site](https://developers.google.com/adsense/host/).
//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/adsensehost4d1).
//! # Features
//!
//! Handle the following *Resources* with ease from the central [hub](struct.AdSenseHost.html)...
//!
//! * [accounts](struct.Account.html)
//! * [*adclients get*](struct.AccountAdclientGetCall.html), [*adclients list*](struct.AccountAdclientListCall.html), [*adunits delete*](struct.AccountAdunitDeleteCall.html), [*adunits get*](struct.AccountAdunitGetCall.html), [*adunits get ad code*](struct.AccountAdunitGetAdCodeCall.html), [*adunits insert*](struct.AccountAdunitInsertCall.html), [*adunits list*](struct.AccountAdunitListCall.html), [*adunits patch*](struct.AccountAdunitPatchCall.html), [*adunits update*](struct.AccountAdunitUpdateCall.html), [*get*](struct.AccountGetCall.html), [*list*](struct.AccountListCall.html) and [*reports generate*](struct.AccountReportGenerateCall.html)
//! * adclients
//! * [*get*](struct.AdclientGetCall.html) and [*list*](struct.AdclientListCall.html)
//! * associationsessions
//! * [*start*](struct.AssociationsessionStartCall.html) and [*verify*](struct.AssociationsessionVerifyCall.html)
//! * customchannels
//! * [*delete*](struct.CustomchannelDeleteCall.html), [*get*](struct.CustomchannelGetCall.html), [*insert*](struct.CustomchannelInsertCall.html), [*list*](struct.CustomchannelListCall.html), [*patch*](struct.CustomchannelPatchCall.html) and [*update*](struct.CustomchannelUpdateCall.html)
//! * [reports](struct.Report.html)
//! * [*generate*](struct.ReportGenerateCall.html)
//! * urlchannels
//! * [*delete*](struct.UrlchannelDeleteCall.html), [*insert*](struct.UrlchannelInsertCall.html) and [*list*](struct.UrlchannelListCall.html)
//!
//!
//!
//!
//! Not what you are looking for? Find all other Google APIs in their Rust [documentation index](../index.html).
//!
//! # Structure of this Library
//!
//! The API is structured into the following primary items:
//!
//! * **[Hub](struct.AdSenseHost.html)**
//! * a central object to maintain state and allow accessing all *Activities*
//! * creates [*Method Builders*](trait.MethodsBuilder.html) which in turn
//! allow access to individual [*Call Builders*](trait.CallBuilder.html)
//! * **[Resources](trait.Resource.html)**
//! * primary types that you can apply *Activities* to
//! * a collection of properties and *Parts*
//! * **[Parts](trait.Part.html)**
//! * a collection of properties
//! * never directly used in *Activities*
//! * **[Activities](trait.CallBuilder.html)**
//! * operations to apply to *Resources*
//!
//! All *structures* are marked with applicable traits to further categorize them and ease browsing.
//!
//! Generally speaking, you can invoke *Activities* like this:
//!
//! ```Rust,ignore
//! let r = hub.resource().activity(...).doit()
//! ```
//!
|
//! let r = hub.accounts().adunits_get(...).doit()
//! let r = hub.accounts().get(...).doit()
//! let r = hub.accounts().adunits_list(...).doit()
//! let r = hub.accounts().adunits_get_ad_code(...).doit()
//! let r = hub.accounts().reports_generate(...).doit()
//! let r = hub.accounts().adunits_delete(...).doit()
//! let r = hub.accounts().adunits_update(...).doit()
//! let r = hub.accounts().adunits_patch(...).doit()
//! let r = hub.accounts().adunits_insert(...).doit()
//! let r = hub.accounts().list(...).doit()
//! let r = hub.accounts().adclients_list(...).doit()
//! let r = hub.accounts().adclients_get(...).doit()
//! ```
//!
//! The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities`
//! supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be
//! specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired.
//! The `doit()` method performs the actual communication with the server and returns the respective result.
//!
//! # Usage
//!
//! ## Setting up your Project
//!
//! To use this library, you would put the following lines into your `Cargo.toml` file:
//!
//! ```toml
//! [dependencies]
//! google-adsensehost4d1 = "*"
//! ```
//!
//! ## A complete example
//!
//! ```test_harness,no_run
//! extern crate hyper;
//! extern crate yup_oauth2 as oauth2;
//! extern crate google_adsensehost4d1 as adsensehost4d1;
//! use adsensehost4d1::{Result, Error};
//! # #[test] fn egal() {
//! use std::default::Default;
//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
//! use adsensehost4d1::AdSenseHost;
//!
//! // Get an ApplicationSecret instance by some means. It contains the `client_id` and
//! // `client_secret`, among other things.
//! let secret: ApplicationSecret = Default::default();
//! // Instantiate the authenticator. It will choose a suitable authentication flow for you,
//! // unless you replace `None` with the desired Flow.
//! // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about
//! // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and
//! // retrieve them from storage.
//! let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
//! hyper::Client::new(),
//! <MemoryStorage as Default>::default(), None);
//! let mut hub = AdSenseHost::new(hyper::Client::new(), auth);
//! // You can configure optional parameters by calling the respective setters at will, and
//! // execute the final call using `doit()`.
//! // Values shown here are possibly random and not representative!
//! let result = hub.accounts().reports_generate("accountId", "startDate", "endDate")
//! .start_index(35)
//! .add_sort("sadipscing")
//! .add_metric("rebum.")
//! .max_results(68)
//! .locale("nonumy")
//! .add_filter("sed")
//! .add_dimension("aliquyam")
//! .doit();
//!
//! match result {
//! Err(e) => match e {
//! // The Error enum provides details about what exactly happened.
//! // You can also just use its `Debug`, `Display` or `Error` traits
//! Error::HttpError(_)
//! |Error::MissingAPIKey
//! |Error::MissingToken(_)
//! |Error::Cancelled
//! |Error::UploadSizeLimitExceeded(_, _)
//! |Error::Failure(_)
//! |Error::BadRequest(_)
//! |Error::FieldClash(_)
//! |Error::JsonDecodeError(_, _) => println!("{}", e),
//! },
//! Ok(res) => println!("Success: {:?}", res),
//! }
//! # }
//! ```
//! ## Handling Errors
//!
//! All errors produced by the system are provided either as [Result](enum.Result.html) enumeration as return value of
//! the doit() methods, or handed as possibly intermediate results to either the
//! [Hub Delegate](trait.Delegate.html), or the [Authenticator Delegate](../yup-oauth2/trait.AuthenticatorDelegate.html).
//!
//! When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This
//! makes the system potentially resilient to all kinds of errors.
//!
//! ## Uploads and Downloads
//! If a method supports downloads, the response body, which is part of the [Result](enum.Result.html), should be
//! read by you to obtain the media.
//! If such a method also supports a [Response Result](trait.ResponseResult.html), it will return that by default.
//! You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making
//! this call: `.param("alt", "media")`.
//!
//! Methods supporting uploads can do so using up to 2 different protocols:
//! *simple* and *resumable*. The distinctiveness of each is represented by customized
//! `doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively.
//!
//! ## Customization and Callbacks
//!
//! You may alter the way an `doit()` method is called by providing a [delegate](trait.Delegate.html) to the
//! [Method Builder](trait.CallBuilder.html) before making the final `doit()` call.
//! Respective methods will be called to provide progress information, as well as determine whether the system should
//! retry on failure.
//!
//! The [delegate trait](trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort.
//!
//! ## Optional Parts in Server-Requests
//!
//! All structures provided by this library are made to be [enocodable](trait.RequestValue.html) and
//! [decodable](trait.ResponseResult.html) via *json*. Optionals are used to indicate that partial requests are responses
//! are valid.
//! Most optionals are are considered [Parts](trait.Part.html) which are identifiable by name, which will be sent to
//! the server to indicate either the set parts of the request or the desired parts in the response.
//!
//! ## Builder Arguments
//!
//! Using [method builders](trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods.
//! These will always take a single argument, for which the following statements are true.
//!
//! * [PODs][wiki-pod] are handed by copy
//! * strings are passed as `&str`
//! * [request values](trait.RequestValue.html) are moved
//!
//! Arguments will always be copied or cloned into the builder, to make them independent of their original life times.
//!
//! [wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure
//! [builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern
//! [google-go-api]: https://github.com/google/google-api-go-client
//!
//!
// Unused attributes happen thanks to defined, but unused structures
// We don't warn about this, as depending on the API, some data structures or facilities are never used.
// Instead of pre-determining this, we just disable the lint. It's manually tuned to not have any
// unused imports in fully featured APIs. Same with unused_mut....
#![allow(unused_imports, unused_mut, dead_code)]
include!(concat!(env!("OUT_DIR"), "/lib.rs"));
|
//! Or specifically ...
//!
//! ```ignore
|
random_line_split
|
borrowck-borrow-mut-base-ptr-in-aliasable-loc.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test that attempt to reborrow an `&mut` pointer in an aliasable
// location yields an error.
//
// Example from src/middle/borrowck/doc.rs
fn foo(t0: & &mut isize)
|
fn foo3(t0: &mut &mut isize) {
let t1 = &mut *t0;
let p: &isize = &**t0; //~ ERROR cannot borrow
**t1 = 22;
}
fn foo4(t0: & &mut isize) {
let x: &mut isize = &mut **t0; //~ ERROR cannot borrow
*x += 1;
}
fn main() {
}
|
{
let t1 = t0;
let p: &isize = &**t0;
**t1 = 22; //~ ERROR cannot assign
}
|
identifier_body
|
borrowck-borrow-mut-base-ptr-in-aliasable-loc.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
|
// Example from src/middle/borrowck/doc.rs
fn foo(t0: & &mut isize) {
let t1 = t0;
let p: &isize = &**t0;
**t1 = 22; //~ ERROR cannot assign
}
fn foo3(t0: &mut &mut isize) {
let t1 = &mut *t0;
let p: &isize = &**t0; //~ ERROR cannot borrow
**t1 = 22;
}
fn foo4(t0: & &mut isize) {
let x: &mut isize = &mut **t0; //~ ERROR cannot borrow
*x += 1;
}
fn main() {
}
|
// except according to those terms.
// Test that attempt to reborrow an `&mut` pointer in an aliasable
// location yields an error.
//
|
random_line_split
|
borrowck-borrow-mut-base-ptr-in-aliasable-loc.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test that attempt to reborrow an `&mut` pointer in an aliasable
// location yields an error.
//
// Example from src/middle/borrowck/doc.rs
fn foo(t0: & &mut isize) {
let t1 = t0;
let p: &isize = &**t0;
**t1 = 22; //~ ERROR cannot assign
}
fn
|
(t0: &mut &mut isize) {
let t1 = &mut *t0;
let p: &isize = &**t0; //~ ERROR cannot borrow
**t1 = 22;
}
fn foo4(t0: & &mut isize) {
let x: &mut isize = &mut **t0; //~ ERROR cannot borrow
*x += 1;
}
fn main() {
}
|
foo3
|
identifier_name
|
cabi_x86.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use syntax::abi::{OsWin32, OsMacos};
use lib::llvm::*;
use super::cabi::*;
use super::common::*;
use super::machine::*;
use middle::trans::type_::Type;
pub fn compute_abi_info(ccx: &CrateContext,
atys: &[Type],
rty: Type,
ret_def: bool) -> FnType
|
2 => RetValue(Type::i16(ccx)),
4 => RetValue(Type::i32(ccx)),
8 => RetValue(Type::i64(ccx)),
_ => RetPointer
}
}
_ => {
RetPointer
}
};
match strategy {
RetValue(t) => {
ret_ty = ArgType::direct(rty, Some(t), None, None);
}
RetPointer => {
ret_ty = ArgType::indirect(rty, Some(StructRetAttribute));
}
}
} else {
ret_ty = ArgType::direct(rty, None, None, None);
}
for &t in atys.iter() {
let ty = match t.kind() {
Struct => {
let size = llsize_of_alloc(ccx, t);
if size == 0 {
ArgType::ignore(t)
} else {
ArgType::indirect(t, Some(ByValAttribute))
}
}
_ => ArgType::direct(t, None, None, None),
};
arg_tys.push(ty);
}
return FnType {
arg_tys: arg_tys,
ret_ty: ret_ty,
};
}
|
{
let mut arg_tys = Vec::new();
let ret_ty;
if !ret_def {
ret_ty = ArgType::direct(Type::void(ccx), None, None, None);
} else if rty.kind() == Struct {
// Returning a structure. Most often, this will use
// a hidden first argument. On some platforms, though,
// small structs are returned as integers.
//
// Some links:
// http://www.angelcode.com/dev/callconv/callconv.html
// Clang's ABI handling is in lib/CodeGen/TargetInfo.cpp
enum Strategy { RetValue(Type), RetPointer }
let strategy = match ccx.sess().targ_cfg.os {
OsWin32 | OsMacos => {
match llsize_of_alloc(ccx, rty) {
1 => RetValue(Type::i8(ccx)),
|
identifier_body
|
cabi_x86.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use syntax::abi::{OsWin32, OsMacos};
use lib::llvm::*;
use super::cabi::*;
use super::common::*;
use super::machine::*;
use middle::trans::type_::Type;
pub fn compute_abi_info(ccx: &CrateContext,
atys: &[Type],
rty: Type,
ret_def: bool) -> FnType {
let mut arg_tys = Vec::new();
let ret_ty;
if!ret_def {
ret_ty = ArgType::direct(Type::void(ccx), None, None, None);
} else if rty.kind() == Struct {
// Returning a structure. Most often, this will use
// a hidden first argument. On some platforms, though,
// small structs are returned as integers.
//
// Some links:
// http://www.angelcode.com/dev/callconv/callconv.html
// Clang's ABI handling is in lib/CodeGen/TargetInfo.cpp
enum Strategy { RetValue(Type), RetPointer }
let strategy = match ccx.sess().targ_cfg.os {
OsWin32 | OsMacos => {
match llsize_of_alloc(ccx, rty) {
1 => RetValue(Type::i8(ccx)),
2 => RetValue(Type::i16(ccx)),
4 => RetValue(Type::i32(ccx)),
8 => RetValue(Type::i64(ccx)),
_ => RetPointer
}
}
_ => {
RetPointer
}
};
match strategy {
RetValue(t) => {
ret_ty = ArgType::direct(rty, Some(t), None, None);
}
RetPointer => {
ret_ty = ArgType::indirect(rty, Some(StructRetAttribute));
}
}
} else
|
for &t in atys.iter() {
let ty = match t.kind() {
Struct => {
let size = llsize_of_alloc(ccx, t);
if size == 0 {
ArgType::ignore(t)
} else {
ArgType::indirect(t, Some(ByValAttribute))
}
}
_ => ArgType::direct(t, None, None, None),
};
arg_tys.push(ty);
}
return FnType {
arg_tys: arg_tys,
ret_ty: ret_ty,
};
}
|
{
ret_ty = ArgType::direct(rty, None, None, None);
}
|
conditional_block
|
cabi_x86.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
|
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use syntax::abi::{OsWin32, OsMacos};
use lib::llvm::*;
use super::cabi::*;
use super::common::*;
use super::machine::*;
use middle::trans::type_::Type;
pub fn compute_abi_info(ccx: &CrateContext,
atys: &[Type],
rty: Type,
ret_def: bool) -> FnType {
let mut arg_tys = Vec::new();
let ret_ty;
if!ret_def {
ret_ty = ArgType::direct(Type::void(ccx), None, None, None);
} else if rty.kind() == Struct {
// Returning a structure. Most often, this will use
// a hidden first argument. On some platforms, though,
// small structs are returned as integers.
//
// Some links:
// http://www.angelcode.com/dev/callconv/callconv.html
// Clang's ABI handling is in lib/CodeGen/TargetInfo.cpp
enum Strategy { RetValue(Type), RetPointer }
let strategy = match ccx.sess().targ_cfg.os {
OsWin32 | OsMacos => {
match llsize_of_alloc(ccx, rty) {
1 => RetValue(Type::i8(ccx)),
2 => RetValue(Type::i16(ccx)),
4 => RetValue(Type::i32(ccx)),
8 => RetValue(Type::i64(ccx)),
_ => RetPointer
}
}
_ => {
RetPointer
}
};
match strategy {
RetValue(t) => {
ret_ty = ArgType::direct(rty, Some(t), None, None);
}
RetPointer => {
ret_ty = ArgType::indirect(rty, Some(StructRetAttribute));
}
}
} else {
ret_ty = ArgType::direct(rty, None, None, None);
}
for &t in atys.iter() {
let ty = match t.kind() {
Struct => {
let size = llsize_of_alloc(ccx, t);
if size == 0 {
ArgType::ignore(t)
} else {
ArgType::indirect(t, Some(ByValAttribute))
}
}
_ => ArgType::direct(t, None, None, None),
};
arg_tys.push(ty);
}
return FnType {
arg_tys: arg_tys,
ret_ty: ret_ty,
};
}
|
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
random_line_split
|
cabi_x86.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use syntax::abi::{OsWin32, OsMacos};
use lib::llvm::*;
use super::cabi::*;
use super::common::*;
use super::machine::*;
use middle::trans::type_::Type;
pub fn compute_abi_info(ccx: &CrateContext,
atys: &[Type],
rty: Type,
ret_def: bool) -> FnType {
let mut arg_tys = Vec::new();
let ret_ty;
if!ret_def {
ret_ty = ArgType::direct(Type::void(ccx), None, None, None);
} else if rty.kind() == Struct {
// Returning a structure. Most often, this will use
// a hidden first argument. On some platforms, though,
// small structs are returned as integers.
//
// Some links:
// http://www.angelcode.com/dev/callconv/callconv.html
// Clang's ABI handling is in lib/CodeGen/TargetInfo.cpp
enum
|
{ RetValue(Type), RetPointer }
let strategy = match ccx.sess().targ_cfg.os {
OsWin32 | OsMacos => {
match llsize_of_alloc(ccx, rty) {
1 => RetValue(Type::i8(ccx)),
2 => RetValue(Type::i16(ccx)),
4 => RetValue(Type::i32(ccx)),
8 => RetValue(Type::i64(ccx)),
_ => RetPointer
}
}
_ => {
RetPointer
}
};
match strategy {
RetValue(t) => {
ret_ty = ArgType::direct(rty, Some(t), None, None);
}
RetPointer => {
ret_ty = ArgType::indirect(rty, Some(StructRetAttribute));
}
}
} else {
ret_ty = ArgType::direct(rty, None, None, None);
}
for &t in atys.iter() {
let ty = match t.kind() {
Struct => {
let size = llsize_of_alloc(ccx, t);
if size == 0 {
ArgType::ignore(t)
} else {
ArgType::indirect(t, Some(ByValAttribute))
}
}
_ => ArgType::direct(t, None, None, None),
};
arg_tys.push(ty);
}
return FnType {
arg_tys: arg_tys,
ret_ty: ret_ty,
};
}
|
Strategy
|
identifier_name
|
image.rs
|
extern crate piston_window;
extern crate find_folder;
use piston_window::*;
|
.exit_on_esc(true)
.opengl(opengl)
.build()
.unwrap();
let assets = find_folder::Search::ParentsThenKids(3, 3)
.for_folder("assets").unwrap();
let rust_logo = assets.join("rust.png");
let rust_logo = Texture::from_path(
&mut *window.factory.borrow_mut(),
&rust_logo,
Flip::None,
&TextureSettings::new()
).unwrap();
for e in window {
e.draw_2d(|c, g| {
clear([1.0; 4], g);
image(&rust_logo, c.transform, g);
});
}
}
|
fn main() {
let opengl = OpenGL::V3_2;
let window: PistonWindow =
WindowSettings::new("piston: image", [300, 300])
|
random_line_split
|
image.rs
|
extern crate piston_window;
extern crate find_folder;
use piston_window::*;
fn main()
|
clear([1.0; 4], g);
image(&rust_logo, c.transform, g);
});
}
}
|
{
let opengl = OpenGL::V3_2;
let window: PistonWindow =
WindowSettings::new("piston: image", [300, 300])
.exit_on_esc(true)
.opengl(opengl)
.build()
.unwrap();
let assets = find_folder::Search::ParentsThenKids(3, 3)
.for_folder("assets").unwrap();
let rust_logo = assets.join("rust.png");
let rust_logo = Texture::from_path(
&mut *window.factory.borrow_mut(),
&rust_logo,
Flip::None,
&TextureSettings::new()
).unwrap();
for e in window {
e.draw_2d(|c, g| {
|
identifier_body
|
image.rs
|
extern crate piston_window;
extern crate find_folder;
use piston_window::*;
fn
|
() {
let opengl = OpenGL::V3_2;
let window: PistonWindow =
WindowSettings::new("piston: image", [300, 300])
.exit_on_esc(true)
.opengl(opengl)
.build()
.unwrap();
let assets = find_folder::Search::ParentsThenKids(3, 3)
.for_folder("assets").unwrap();
let rust_logo = assets.join("rust.png");
let rust_logo = Texture::from_path(
&mut *window.factory.borrow_mut(),
&rust_logo,
Flip::None,
&TextureSettings::new()
).unwrap();
for e in window {
e.draw_2d(|c, g| {
clear([1.0; 4], g);
image(&rust_logo, c.transform, g);
});
}
}
|
main
|
identifier_name
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.