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 |
---|---|---|---|---|
sr_masterctl.rs | // SairaDB - A distributed database
// Copyright (C) 2015 by Siyu Wang
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
use std::collections::HashMap;
use std::net::TcpStream;
use std::thread;
use std::sync::Arc;
use std::sync::mpsc::Sender;
use std::sync::atomic::AtomicUsize;
use super::libc;
pub fn init(masters: Vec<String>, vnodes: Vec<u64>,
map: &HashMap<String, String>, log_sender: Sender<String>) {
let vnodes = Arc::new(vnodes);
let cookie = map.get("cookie-master").unwrap().to_string();
let port = map.get("master-port").unwrap().to_string();
for master in masters {
let vnodes = vnodes.clone();
let log_sender = log_sender.clone();
let master = master.to_string();
let cookie = cookie.to_string();
let port = port.to_string();
let _ = thread::Builder::new().name(format!("master_task({})", master))
.spawn(|| {
master_task(master, port, vnodes, cookie, log_sender);
});
}
}
fn master_task(ip: String, port: String, vnodes: Arc<Vec<u64>>, cookie: String,
log_sender: Sender<String>) { |
let stream = TcpStream::connect(addr);
//match stream.write_all(cookie.as_bytes());
}
}
fn master_connection() {
} | let addr: &str = &(ip + ":" + &port);
let count = Arc::new(AtomicUsize::new(0));
loop { | random_line_split |
diepdma0.rs | #[doc = "Register `DIEPDMA0` reader"]
pub struct R(crate::R<DIEPDMA0_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<DIEPDMA0_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<DIEPDMA0_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<DIEPDMA0_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `DIEPDMA0` writer"]
pub struct W(crate::W<DIEPDMA0_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<DIEPDMA0_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for W {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl From<crate::W<DIEPDMA0_SPEC>> for W {
#[inline(always)]
fn from(writer: crate::W<DIEPDMA0_SPEC>) -> Self {
W(writer)
}
}
#[doc = "Field `DMAAddr` reader - DMA Address"]
pub struct DMAADDR_R(crate::FieldReader<u32, u32>);
impl DMAADDR_R {
pub(crate) fn new(bits: u32) -> Self {
DMAADDR_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for DMAADDR_R {
type Target = crate::FieldReader<u32, u32>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `DMAAddr` writer - DMA Address"]
pub struct DMAADDR_W<'a> {
w: &'a mut W,
}
impl<'a> DMAADDR_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u32) -> &'a mut W {
self.w.bits = (self.w.bits &!0xffff_ffff) | (value as u32 & 0xffff_ffff);
self.w
}
}
impl R {
#[doc = "Bits 0:31 - DMA Address"]
#[inline(always)]
pub fn | (&self) -> DMAADDR_R {
DMAADDR_R::new((self.bits & 0xffff_ffff) as u32)
}
}
impl W {
#[doc = "Bits 0:31 - DMA Address"]
#[inline(always)]
pub fn dmaaddr(&mut self) -> DMAADDR_W {
DMAADDR_W { w: self }
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.0.bits(bits);
self
}
}
#[doc = "Device Endpoint DMA Address Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [diepdma0](index.html) module"]
pub struct DIEPDMA0_SPEC;
impl crate::RegisterSpec for DIEPDMA0_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [diepdma0::R](R) reader structure"]
impl crate::Readable for DIEPDMA0_SPEC {
type Reader = R;
}
#[doc = "`write(|w|..)` method takes [diepdma0::W](W) writer structure"]
impl crate::Writable for DIEPDMA0_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets DIEPDMA0 to value 0"]
impl crate::Resettable for DIEPDMA0_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
}
| dmaaddr | identifier_name |
diepdma0.rs | #[doc = "Register `DIEPDMA0` reader"]
pub struct R(crate::R<DIEPDMA0_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<DIEPDMA0_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<DIEPDMA0_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<DIEPDMA0_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `DIEPDMA0` writer"]
pub struct W(crate::W<DIEPDMA0_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<DIEPDMA0_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for W {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl From<crate::W<DIEPDMA0_SPEC>> for W {
#[inline(always)]
fn from(writer: crate::W<DIEPDMA0_SPEC>) -> Self {
W(writer)
}
}
#[doc = "Field `DMAAddr` reader - DMA Address"]
pub struct DMAADDR_R(crate::FieldReader<u32, u32>); | impl core::ops::Deref for DMAADDR_R {
type Target = crate::FieldReader<u32, u32>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `DMAAddr` writer - DMA Address"]
pub struct DMAADDR_W<'a> {
w: &'a mut W,
}
impl<'a> DMAADDR_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u32) -> &'a mut W {
self.w.bits = (self.w.bits &!0xffff_ffff) | (value as u32 & 0xffff_ffff);
self.w
}
}
impl R {
#[doc = "Bits 0:31 - DMA Address"]
#[inline(always)]
pub fn dmaaddr(&self) -> DMAADDR_R {
DMAADDR_R::new((self.bits & 0xffff_ffff) as u32)
}
}
impl W {
#[doc = "Bits 0:31 - DMA Address"]
#[inline(always)]
pub fn dmaaddr(&mut self) -> DMAADDR_W {
DMAADDR_W { w: self }
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.0.bits(bits);
self
}
}
#[doc = "Device Endpoint DMA Address Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [diepdma0](index.html) module"]
pub struct DIEPDMA0_SPEC;
impl crate::RegisterSpec for DIEPDMA0_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [diepdma0::R](R) reader structure"]
impl crate::Readable for DIEPDMA0_SPEC {
type Reader = R;
}
#[doc = "`write(|w|..)` method takes [diepdma0::W](W) writer structure"]
impl crate::Writable for DIEPDMA0_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets DIEPDMA0 to value 0"]
impl crate::Resettable for DIEPDMA0_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
} | impl DMAADDR_R {
pub(crate) fn new(bits: u32) -> Self {
DMAADDR_R(crate::FieldReader::new(bits))
}
} | random_line_split |
borrowck-lend-flow-loop.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.
// Note: the borrowck analysis is currently flow-insensitive.
// Therefore, some of these errors are marked as spurious and could be
// corrected by a simple change to the analysis. The others are
// either genuine or would require more advanced changes. The latter
// cases are noted.
#![feature(box_syntax)]
fn borrow(_v: &int) {}
fn borrow_mut(_v: &mut int) |
fn cond() -> bool { panic!() }
fn produce<T>() -> T { panic!(); }
fn inc(v: &mut Box<int>) {
*v = box() (**v + 1);
}
fn loop_overarching_alias_mut() {
// In this instance, the borrow encompasses the entire loop.
let mut v = box 3;
let mut x = &mut v;
**x += 1;
loop {
borrow(&*v); //~ ERROR cannot borrow
}
}
fn block_overarching_alias_mut() {
// In this instance, the borrow encompasses the entire closure call.
let mut v = box 3;
let mut x = &mut v;
for _ in range(0i, 3) {
borrow(&*v); //~ ERROR cannot borrow
}
*x = box 5;
}
fn loop_aliased_mut() {
// In this instance, the borrow is carried through the loop.
let mut v = box 3;
let mut w = box 4;
let mut _x = &w;
loop {
borrow_mut(&mut *v); //~ ERROR cannot borrow
_x = &v;
}
}
fn while_aliased_mut() {
// In this instance, the borrow is carried through the loop.
let mut v = box 3;
let mut w = box 4;
let mut _x = &w;
while cond() {
borrow_mut(&mut *v); //~ ERROR cannot borrow
_x = &v;
}
}
fn loop_aliased_mut_break() {
// In this instance, the borrow is carried through the loop.
let mut v = box 3;
let mut w = box 4;
let mut _x = &w;
loop {
borrow_mut(&mut *v);
_x = &v;
break;
}
borrow_mut(&mut *v); //~ ERROR cannot borrow
}
fn while_aliased_mut_break() {
// In this instance, the borrow is carried through the loop.
let mut v = box 3;
let mut w = box 4;
let mut _x = &w;
while cond() {
borrow_mut(&mut *v);
_x = &v;
break;
}
borrow_mut(&mut *v); //~ ERROR cannot borrow
}
fn while_aliased_mut_cond(cond: bool, cond2: bool) {
let mut v = box 3;
let mut w = box 4;
let mut x = &mut w;
while cond {
**x += 1;
borrow(&*v); //~ ERROR cannot borrow
if cond2 {
x = &mut v; //~ ERROR cannot borrow
}
}
}
fn loop_break_pops_scopes<'r, F>(_v: &'r mut [uint], mut f: F) where
F: FnMut(&'r mut uint) -> bool,
{
// Here we check that when you break out of an inner loop, the
// borrows that go out of scope as you exit the inner loop are
// removed from the bitset.
while cond() {
while cond() {
// this borrow is limited to the scope of `r`...
let r: &'r mut uint = produce();
if!f(&mut *r) {
break; //...so it is not live as exit the `while` loop here
}
}
}
}
fn loop_loop_pops_scopes<'r, F>(_v: &'r mut [uint], mut f: F) where F: FnMut(&'r mut uint) -> bool {
// Similar to `loop_break_pops_scopes` but for the `loop` keyword
while cond() {
while cond() {
// this borrow is limited to the scope of `r`...
let r: &'r mut uint = produce();
if!f(&mut *r) {
continue; //...so it is not live as exit (and re-enter) the `while` loop here
}
}
}
}
fn main() {}
| {} | identifier_body |
borrowck-lend-flow-loop.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.
// Note: the borrowck analysis is currently flow-insensitive.
// Therefore, some of these errors are marked as spurious and could be
// corrected by a simple change to the analysis. The others are
// either genuine or would require more advanced changes. The latter
// cases are noted.
#![feature(box_syntax)]
fn borrow(_v: &int) {}
fn borrow_mut(_v: &mut int) {}
fn cond() -> bool { panic!() }
fn produce<T>() -> T { panic!(); }
fn inc(v: &mut Box<int>) {
*v = box() (**v + 1);
}
fn loop_overarching_alias_mut() {
// In this instance, the borrow encompasses the entire loop.
let mut v = box 3;
let mut x = &mut v;
**x += 1;
loop {
borrow(&*v); //~ ERROR cannot borrow
}
}
fn block_overarching_alias_mut() {
// In this instance, the borrow encompasses the entire closure call.
let mut v = box 3;
let mut x = &mut v;
for _ in range(0i, 3) {
borrow(&*v); //~ ERROR cannot borrow
}
*x = box 5;
}
fn loop_aliased_mut() {
// In this instance, the borrow is carried through the loop.
let mut v = box 3;
let mut w = box 4;
let mut _x = &w;
loop {
borrow_mut(&mut *v); //~ ERROR cannot borrow
_x = &v;
}
}
fn while_aliased_mut() {
// In this instance, the borrow is carried through the loop.
let mut v = box 3;
let mut w = box 4;
let mut _x = &w;
while cond() {
borrow_mut(&mut *v); //~ ERROR cannot borrow
_x = &v;
}
}
fn loop_aliased_mut_break() {
// In this instance, the borrow is carried through the loop.
let mut v = box 3;
let mut w = box 4;
let mut _x = &w;
loop {
borrow_mut(&mut *v);
_x = &v;
break;
}
borrow_mut(&mut *v); //~ ERROR cannot borrow
}
fn while_aliased_mut_break() {
// In this instance, the borrow is carried through the loop.
let mut v = box 3;
let mut w = box 4;
let mut _x = &w;
while cond() {
borrow_mut(&mut *v);
_x = &v;
break;
}
borrow_mut(&mut *v); //~ ERROR cannot borrow
}
fn while_aliased_mut_cond(cond: bool, cond2: bool) {
let mut v = box 3;
let mut w = box 4;
let mut x = &mut w;
while cond {
**x += 1;
borrow(&*v); //~ ERROR cannot borrow
if cond2 {
x = &mut v; //~ ERROR cannot borrow
}
}
}
fn loop_break_pops_scopes<'r, F>(_v: &'r mut [uint], mut f: F) where
F: FnMut(&'r mut uint) -> bool,
{
// Here we check that when you break out of an inner loop, the
// borrows that go out of scope as you exit the inner loop are
// removed from the bitset.
while cond() {
while cond() {
// this borrow is limited to the scope of `r`...
let r: &'r mut uint = produce();
if!f(&mut *r) |
}
}
}
fn loop_loop_pops_scopes<'r, F>(_v: &'r mut [uint], mut f: F) where F: FnMut(&'r mut uint) -> bool {
// Similar to `loop_break_pops_scopes` but for the `loop` keyword
while cond() {
while cond() {
// this borrow is limited to the scope of `r`...
let r: &'r mut uint = produce();
if!f(&mut *r) {
continue; //...so it is not live as exit (and re-enter) the `while` loop here
}
}
}
}
fn main() {}
| {
break; // ...so it is not live as exit the `while` loop here
} | conditional_block |
borrowck-lend-flow-loop.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.
// Note: the borrowck analysis is currently flow-insensitive.
// Therefore, some of these errors are marked as spurious and could be
// corrected by a simple change to the analysis. The others are
// either genuine or would require more advanced changes. The latter
// cases are noted.
#![feature(box_syntax)]
fn borrow(_v: &int) {}
fn borrow_mut(_v: &mut int) {}
fn cond() -> bool { panic!() }
fn produce<T>() -> T { panic!(); }
fn inc(v: &mut Box<int>) {
*v = box() (**v + 1);
}
fn loop_overarching_alias_mut() {
// In this instance, the borrow encompasses the entire loop.
let mut v = box 3;
let mut x = &mut v;
**x += 1;
loop {
borrow(&*v); //~ ERROR cannot borrow
}
}
fn block_overarching_alias_mut() {
// In this instance, the borrow encompasses the entire closure call.
let mut v = box 3;
let mut x = &mut v;
for _ in range(0i, 3) {
borrow(&*v); //~ ERROR cannot borrow
}
*x = box 5;
}
fn loop_aliased_mut() {
// In this instance, the borrow is carried through the loop.
let mut v = box 3;
let mut w = box 4;
let mut _x = &w;
loop {
borrow_mut(&mut *v); //~ ERROR cannot borrow
_x = &v;
}
}
fn while_aliased_mut() {
// In this instance, the borrow is carried through the loop.
let mut v = box 3;
let mut w = box 4;
let mut _x = &w;
while cond() {
borrow_mut(&mut *v); //~ ERROR cannot borrow
_x = &v;
}
}
fn loop_aliased_mut_break() {
// In this instance, the borrow is carried through the loop.
let mut v = box 3;
let mut w = box 4;
let mut _x = &w;
loop {
borrow_mut(&mut *v);
_x = &v;
break;
}
borrow_mut(&mut *v); //~ ERROR cannot borrow
}
fn while_aliased_mut_break() {
// In this instance, the borrow is carried through the loop.
let mut v = box 3;
let mut w = box 4;
let mut _x = &w;
while cond() {
borrow_mut(&mut *v);
_x = &v;
break;
}
borrow_mut(&mut *v); //~ ERROR cannot borrow
}
fn while_aliased_mut_cond(cond: bool, cond2: bool) {
let mut v = box 3;
let mut w = box 4;
let mut x = &mut w;
while cond {
**x += 1;
borrow(&*v); //~ ERROR cannot borrow
if cond2 {
x = &mut v; //~ ERROR cannot borrow
}
}
}
fn loop_break_pops_scopes<'r, F>(_v: &'r mut [uint], mut f: F) where
F: FnMut(&'r mut uint) -> bool,
{
// Here we check that when you break out of an inner loop, the
// borrows that go out of scope as you exit the inner loop are
// removed from the bitset.
while cond() {
while cond() {
// this borrow is limited to the scope of `r`...
let r: &'r mut uint = produce();
if!f(&mut *r) {
break; //...so it is not live as exit the `while` loop here
}
}
}
}
fn | <'r, F>(_v: &'r mut [uint], mut f: F) where F: FnMut(&'r mut uint) -> bool {
// Similar to `loop_break_pops_scopes` but for the `loop` keyword
while cond() {
while cond() {
// this borrow is limited to the scope of `r`...
let r: &'r mut uint = produce();
if!f(&mut *r) {
continue; //...so it is not live as exit (and re-enter) the `while` loop here
}
}
}
}
fn main() {}
| loop_loop_pops_scopes | identifier_name |
borrowck-lend-flow-loop.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.
// Note: the borrowck analysis is currently flow-insensitive.
// Therefore, some of these errors are marked as spurious and could be
// corrected by a simple change to the analysis. The others are
// either genuine or would require more advanced changes. The latter
// cases are noted.
#![feature(box_syntax)]
fn borrow(_v: &int) {}
fn borrow_mut(_v: &mut int) {}
fn cond() -> bool { panic!() }
fn produce<T>() -> T { panic!(); }
fn inc(v: &mut Box<int>) {
*v = box() (**v + 1);
}
fn loop_overarching_alias_mut() {
// In this instance, the borrow encompasses the entire loop.
let mut v = box 3;
let mut x = &mut v;
**x += 1;
loop {
borrow(&*v); //~ ERROR cannot borrow
}
}
fn block_overarching_alias_mut() {
// In this instance, the borrow encompasses the entire closure call.
let mut v = box 3;
let mut x = &mut v;
for _ in range(0i, 3) {
borrow(&*v); //~ ERROR cannot borrow
}
*x = box 5;
}
fn loop_aliased_mut() {
// In this instance, the borrow is carried through the loop.
let mut v = box 3;
let mut w = box 4;
let mut _x = &w;
loop {
borrow_mut(&mut *v); //~ ERROR cannot borrow
_x = &v;
}
}
fn while_aliased_mut() {
// In this instance, the borrow is carried through the loop.
let mut v = box 3;
let mut w = box 4;
let mut _x = &w;
while cond() {
borrow_mut(&mut *v); //~ ERROR cannot borrow
_x = &v;
}
}
fn loop_aliased_mut_break() {
// In this instance, the borrow is carried through the loop.
let mut v = box 3;
let mut w = box 4;
let mut _x = &w;
loop {
borrow_mut(&mut *v);
_x = &v;
break;
}
borrow_mut(&mut *v); //~ ERROR cannot borrow
}
fn while_aliased_mut_break() {
// In this instance, the borrow is carried through the loop.
let mut v = box 3;
let mut w = box 4;
let mut _x = &w;
while cond() {
borrow_mut(&mut *v);
_x = &v;
break;
}
borrow_mut(&mut *v); //~ ERROR cannot borrow
}
fn while_aliased_mut_cond(cond: bool, cond2: bool) {
let mut v = box 3;
let mut w = box 4;
let mut x = &mut w;
while cond {
**x += 1;
borrow(&*v); //~ ERROR cannot borrow
if cond2 {
x = &mut v; //~ ERROR cannot borrow
}
}
}
fn loop_break_pops_scopes<'r, F>(_v: &'r mut [uint], mut f: F) where
F: FnMut(&'r mut uint) -> bool,
{
// Here we check that when you break out of an inner loop, the
// borrows that go out of scope as you exit the inner loop are
// removed from the bitset.
while cond() {
while cond() {
// this borrow is limited to the scope of `r`...
let r: &'r mut uint = produce();
if!f(&mut *r) {
break; //...so it is not live as exit the `while` loop here
}
}
}
}
fn loop_loop_pops_scopes<'r, F>(_v: &'r mut [uint], mut f: F) where F: FnMut(&'r mut uint) -> bool {
// Similar to `loop_break_pops_scopes` but for the `loop` keyword
while cond() {
while cond() { | // this borrow is limited to the scope of `r`...
let r: &'r mut uint = produce();
if!f(&mut *r) {
continue; //...so it is not live as exit (and re-enter) the `while` loop here
}
}
}
}
fn main() {} | random_line_split |
|
source_loc_macros.rs | // This test makes sure that different expansions of the file!(), line!(),
// column!() macros get picked up by the incr. comp. hash.
// revisions:rpass1 rpass2
// compile-flags: -Z query-dep-graph
#![feature(rustc_attrs)]
#[rustc_clean(cfg="rpass2")]
fn line_same() {
let _ = line!();
}
#[rustc_clean(cfg="rpass2")]
fn col_same() {
let _ = column!();
}
#[rustc_clean(cfg="rpass2")]
fn file_same() {
let _ = file!();
}
#[rustc_clean(except="hir_owner_nodes,optimized_mir", cfg="rpass2")]
fn line_different() {
#[cfg(rpass1)]
{
let _ = line!();
}
#[cfg(rpass2)]
{
let _ = line!();
}
}
#[rustc_clean(except="hir_owner_nodes,optimized_mir", cfg="rpass2")]
fn | () {
#[cfg(rpass1)]
{
let _ = column!();
}
#[cfg(rpass2)]
{
let _ = column!();
}
}
fn main() {
line_same();
line_different();
col_same();
col_different();
file_same();
}
| col_different | identifier_name |
source_loc_macros.rs | // This test makes sure that different expansions of the file!(), line!(),
// column!() macros get picked up by the incr. comp. hash.
// revisions:rpass1 rpass2
// compile-flags: -Z query-dep-graph
#![feature(rustc_attrs)]
#[rustc_clean(cfg="rpass2")]
fn line_same() {
let _ = line!();
}
#[rustc_clean(cfg="rpass2")]
fn col_same() {
let _ = column!();
}
#[rustc_clean(cfg="rpass2")]
fn file_same() {
let _ = file!();
}
#[rustc_clean(except="hir_owner_nodes,optimized_mir", cfg="rpass2")]
fn line_different() {
#[cfg(rpass1)]
{
let _ = line!();
}
#[cfg(rpass2)]
{
let _ = line!(); | fn col_different() {
#[cfg(rpass1)]
{
let _ = column!();
}
#[cfg(rpass2)]
{
let _ = column!();
}
}
fn main() {
line_same();
line_different();
col_same();
col_different();
file_same();
} | }
}
#[rustc_clean(except="hir_owner_nodes,optimized_mir", cfg="rpass2")] | random_line_split |
source_loc_macros.rs | // This test makes sure that different expansions of the file!(), line!(),
// column!() macros get picked up by the incr. comp. hash.
// revisions:rpass1 rpass2
// compile-flags: -Z query-dep-graph
#![feature(rustc_attrs)]
#[rustc_clean(cfg="rpass2")]
fn line_same() {
let _ = line!();
}
#[rustc_clean(cfg="rpass2")]
fn col_same() {
let _ = column!();
}
#[rustc_clean(cfg="rpass2")]
fn file_same() {
let _ = file!();
}
#[rustc_clean(except="hir_owner_nodes,optimized_mir", cfg="rpass2")]
fn line_different() {
#[cfg(rpass1)]
{
let _ = line!();
}
#[cfg(rpass2)]
{
let _ = line!();
}
}
#[rustc_clean(except="hir_owner_nodes,optimized_mir", cfg="rpass2")]
fn col_different() {
#[cfg(rpass1)]
{
let _ = column!();
}
#[cfg(rpass2)]
{
let _ = column!();
}
}
fn main() | {
line_same();
line_different();
col_same();
col_different();
file_same();
} | identifier_body |
|
insert_only.rs | use std::borrow::Borrow;
use std::boxed::Box;
use std::cell::{Cell, UnsafeCell};
use std::cmp::Eq;
use std::collections::hash_map::{self, Entry};
use std::collections::HashMap as Interior;
use std::hash::{BuildHasher, Hash};
#[derive(Debug)]
pub struct HashMap<K: Eq + Hash, V, S: BuildHasher = ::std::collections::hash_map::RandomState> {
data: UnsafeCell<Interior<K, Box<V>, S>>,
inserting: Cell<bool>,
}
impl<K: Eq + Hash, V> HashMap<K, V, ::std::collections::hash_map::RandomState> {
pub fn new() -> HashMap<K, V, ::std::collections::hash_map::RandomState> |
}
impl<K: Eq + Hash, V, S: BuildHasher> HashMap<K, V, S> {
pub fn with_hasher(hash_builder: S) -> HashMap<K, V, S> {
HashMap {
data: UnsafeCell::new(Interior::with_hasher(hash_builder)),
inserting: Cell::new(false),
}
}
pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> HashMap<K, V, S> {
HashMap {
data: UnsafeCell::new(Interior::with_capacity_and_hasher(capacity, hash_builder)),
inserting: Cell::new(false),
}
}
pub fn get_default<F>(&self, key: K, default_function: F) -> Option<&V>
where
F: FnOnce() -> Option<V>,
{
assert!(
!self.inserting.get(),
"Attempt to call get_default() on a insert_only::HashMap within the default_function \
callback for another get_default() on the same map"
);
self.inserting.set(true);
let result = match unsafe { (*self.data.get()).entry(key) } {
Entry::Vacant(entry) => match default_function() {
None => None,
Some(value) => Some((*entry.insert(Box::new(value))).borrow()),
},
Entry::Occupied(entry) => Some((*entry.into_mut()).borrow()),
};
self.inserting.set(false);
result
}
// if you are holding a &mut HashMap, you can also use it like a regular map
pub fn insert(&mut self, key: K, value: V) -> Option<V> {
unsafe { (*self.data.get()).insert(key, Box::new(value)) }.map(|something| *something)
}
pub fn len(&self) -> usize {
assert!(
!self.inserting.get(),
"Attempt to call len() on a insert_only::HashMap within the default_function \
callback for a get_default() on the same map"
);
unsafe { (*self.data.get()).len() }
}
}
impl<K: Eq + Hash, V, S: BuildHasher + Default> Default for HashMap<K, V, S> {
fn default() -> HashMap<K, V, S> {
HashMap::with_hasher(Default::default())
}
}
pub struct IntoIter<K, V> {
data: hash_map::IntoIter<K, Box<V>>,
}
impl<K, V> Iterator for IntoIter<K, V> {
type Item = (K, V);
fn next(&mut self) -> Option<Self::Item> {
self.data.next().map(|(key, value)| (key, *value))
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.data.size_hint()
}
}
impl<K: Eq + Hash, V, S: BuildHasher> IntoIterator for HashMap<K, V, S> {
type Item = (K, V);
type IntoIter = IntoIter<K, V>;
fn into_iter(self) -> Self::IntoIter {
IntoIter {
data: self.data.into_inner().into_iter(),
}
}
}
| {
HashMap {
data: UnsafeCell::new(Interior::new()),
inserting: Cell::new(false),
}
} | identifier_body |
insert_only.rs | use std::borrow::Borrow;
use std::boxed::Box;
use std::cell::{Cell, UnsafeCell};
use std::cmp::Eq;
use std::collections::hash_map::{self, Entry};
use std::collections::HashMap as Interior;
use std::hash::{BuildHasher, Hash};
#[derive(Debug)]
pub struct HashMap<K: Eq + Hash, V, S: BuildHasher = ::std::collections::hash_map::RandomState> {
data: UnsafeCell<Interior<K, Box<V>, S>>,
inserting: Cell<bool>,
}
impl<K: Eq + Hash, V> HashMap<K, V, ::std::collections::hash_map::RandomState> {
pub fn new() -> HashMap<K, V, ::std::collections::hash_map::RandomState> {
HashMap {
data: UnsafeCell::new(Interior::new()),
inserting: Cell::new(false),
}
}
}
impl<K: Eq + Hash, V, S: BuildHasher> HashMap<K, V, S> {
pub fn with_hasher(hash_builder: S) -> HashMap<K, V, S> {
HashMap {
data: UnsafeCell::new(Interior::with_hasher(hash_builder)),
inserting: Cell::new(false),
}
}
pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> HashMap<K, V, S> {
HashMap {
data: UnsafeCell::new(Interior::with_capacity_and_hasher(capacity, hash_builder)),
inserting: Cell::new(false),
} | }
pub fn get_default<F>(&self, key: K, default_function: F) -> Option<&V>
where
F: FnOnce() -> Option<V>,
{
assert!(
!self.inserting.get(),
"Attempt to call get_default() on a insert_only::HashMap within the default_function \
callback for another get_default() on the same map"
);
self.inserting.set(true);
let result = match unsafe { (*self.data.get()).entry(key) } {
Entry::Vacant(entry) => match default_function() {
None => None,
Some(value) => Some((*entry.insert(Box::new(value))).borrow()),
},
Entry::Occupied(entry) => Some((*entry.into_mut()).borrow()),
};
self.inserting.set(false);
result
}
// if you are holding a &mut HashMap, you can also use it like a regular map
pub fn insert(&mut self, key: K, value: V) -> Option<V> {
unsafe { (*self.data.get()).insert(key, Box::new(value)) }.map(|something| *something)
}
pub fn len(&self) -> usize {
assert!(
!self.inserting.get(),
"Attempt to call len() on a insert_only::HashMap within the default_function \
callback for a get_default() on the same map"
);
unsafe { (*self.data.get()).len() }
}
}
impl<K: Eq + Hash, V, S: BuildHasher + Default> Default for HashMap<K, V, S> {
fn default() -> HashMap<K, V, S> {
HashMap::with_hasher(Default::default())
}
}
pub struct IntoIter<K, V> {
data: hash_map::IntoIter<K, Box<V>>,
}
impl<K, V> Iterator for IntoIter<K, V> {
type Item = (K, V);
fn next(&mut self) -> Option<Self::Item> {
self.data.next().map(|(key, value)| (key, *value))
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.data.size_hint()
}
}
impl<K: Eq + Hash, V, S: BuildHasher> IntoIterator for HashMap<K, V, S> {
type Item = (K, V);
type IntoIter = IntoIter<K, V>;
fn into_iter(self) -> Self::IntoIter {
IntoIter {
data: self.data.into_inner().into_iter(),
}
}
} | random_line_split |
|
insert_only.rs | use std::borrow::Borrow;
use std::boxed::Box;
use std::cell::{Cell, UnsafeCell};
use std::cmp::Eq;
use std::collections::hash_map::{self, Entry};
use std::collections::HashMap as Interior;
use std::hash::{BuildHasher, Hash};
#[derive(Debug)]
pub struct HashMap<K: Eq + Hash, V, S: BuildHasher = ::std::collections::hash_map::RandomState> {
data: UnsafeCell<Interior<K, Box<V>, S>>,
inserting: Cell<bool>,
}
impl<K: Eq + Hash, V> HashMap<K, V, ::std::collections::hash_map::RandomState> {
pub fn new() -> HashMap<K, V, ::std::collections::hash_map::RandomState> {
HashMap {
data: UnsafeCell::new(Interior::new()),
inserting: Cell::new(false),
}
}
}
impl<K: Eq + Hash, V, S: BuildHasher> HashMap<K, V, S> {
pub fn with_hasher(hash_builder: S) -> HashMap<K, V, S> {
HashMap {
data: UnsafeCell::new(Interior::with_hasher(hash_builder)),
inserting: Cell::new(false),
}
}
pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> HashMap<K, V, S> {
HashMap {
data: UnsafeCell::new(Interior::with_capacity_and_hasher(capacity, hash_builder)),
inserting: Cell::new(false),
}
}
pub fn get_default<F>(&self, key: K, default_function: F) -> Option<&V>
where
F: FnOnce() -> Option<V>,
{
assert!(
!self.inserting.get(),
"Attempt to call get_default() on a insert_only::HashMap within the default_function \
callback for another get_default() on the same map"
);
self.inserting.set(true);
let result = match unsafe { (*self.data.get()).entry(key) } {
Entry::Vacant(entry) => match default_function() {
None => None,
Some(value) => Some((*entry.insert(Box::new(value))).borrow()),
},
Entry::Occupied(entry) => Some((*entry.into_mut()).borrow()),
};
self.inserting.set(false);
result
}
// if you are holding a &mut HashMap, you can also use it like a regular map
pub fn insert(&mut self, key: K, value: V) -> Option<V> {
unsafe { (*self.data.get()).insert(key, Box::new(value)) }.map(|something| *something)
}
pub fn len(&self) -> usize {
assert!(
!self.inserting.get(),
"Attempt to call len() on a insert_only::HashMap within the default_function \
callback for a get_default() on the same map"
);
unsafe { (*self.data.get()).len() }
}
}
impl<K: Eq + Hash, V, S: BuildHasher + Default> Default for HashMap<K, V, S> {
fn default() -> HashMap<K, V, S> {
HashMap::with_hasher(Default::default())
}
}
pub struct IntoIter<K, V> {
data: hash_map::IntoIter<K, Box<V>>,
}
impl<K, V> Iterator for IntoIter<K, V> {
type Item = (K, V);
fn next(&mut self) -> Option<Self::Item> {
self.data.next().map(|(key, value)| (key, *value))
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.data.size_hint()
}
}
impl<K: Eq + Hash, V, S: BuildHasher> IntoIterator for HashMap<K, V, S> {
type Item = (K, V);
type IntoIter = IntoIter<K, V>;
fn | (self) -> Self::IntoIter {
IntoIter {
data: self.data.into_inner().into_iter(),
}
}
}
| into_iter | identifier_name |
metadata.rs | use std::collections::HashMap;
use std::ops::{Deref, DerefMut};
use super::Error;
use crate::Error::MalformedMetadata;
#[derive(Debug)]
pub struct MetadataMap<'a>(HashMap<&'a str, &'a str>);
impl<'a> MetadataMap<'a> {
/// Returns a string that indicates the character set.
pub fn charset(&self) -> Option<&'a str> {
self.get("Content-Type")
.and_then(|x| x.split("charset=").nth(1))
}
/// Returns the number of different plurals and the boolean
/// expression to determine the form to use depending on
/// the number of elements.
///
/// Defaults to `n_plurals = 2` and `plural = n!=1` (as in English).
pub fn plural_forms(&self) -> (Option<usize>, Option<&'a str>) {
self.get("Plural-Forms")
.map(|f| {
f.split(';').fold((None, None), |(n_pl, pl), prop| {
match prop.chars().position(|c| c == '=') {
Some(index) => {
let (name, value) = prop.split_at(index);
let value = value[1..value.len()].trim();
match name.trim() {
"n_plurals" => (usize::from_str_radix(value, 10).ok(), pl),
"plural" => (n_pl, Some(value)),
_ => (n_pl, pl),
}
}
None => (n_pl, pl),
}
})
})
.unwrap_or((None, None))
}
}
impl<'a> Deref for MetadataMap<'a> {
type Target = HashMap<&'a str, &'a str>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<'a> DerefMut for MetadataMap<'a> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
pub fn parse_metadata(blob: &str) -> Result<MetadataMap, Error> {
let mut map = MetadataMap(HashMap::new());
for line in blob.split('\n').filter(|s| s!= &"") {
let pos = match line.bytes().position(|b| b == b':') {
Some(p) => p,
None => return Err(MalformedMetadata),
};
map.insert(line[..pos].trim(), line[pos + 1..].trim());
}
Ok(map)
}
#[test]
fn test_metadatamap_charset() {
{
let mut map = MetadataMap(HashMap::new());
assert!(map.charset().is_none());
map.insert("Content-Type", "");
assert!(map.charset().is_none());
map.insert("Content-Type", "abc");
assert!(map.charset().is_none());
map.insert("Content-Type", "text/plain; charset=utf-42");
assert_eq!(map.charset().unwrap(), "utf-42");
}
}
#[test]
fn test_metadatamap_plural() {
{
let mut map = MetadataMap(HashMap::new());
assert_eq!(map.plural_forms(), (None, None));
map.insert("Plural-Forms", "");
assert_eq!(map.plural_forms(), (None, None));
// n_plural
map.insert("Plural-Forms", "n_plurals=42");
assert_eq!(map.plural_forms(), (Some(42), None));
// plural is specified
map.insert("Plural-Forms", "n_plurals=2; plural=n==12");
assert_eq!(map.plural_forms(), (Some(2), Some("n==12")));
// plural before n_plurals
map.insert("Plural-Forms", "plural=n==12; n_plurals=2");
assert_eq!(map.plural_forms(), (Some(2), Some("n==12")));
// with spaces | }
} | map.insert("Plural-Forms", " n_plurals = 42 ; plural = n > 10 ");
assert_eq!(map.plural_forms(), (Some(42), Some("n > 10"))); | random_line_split |
metadata.rs | use std::collections::HashMap;
use std::ops::{Deref, DerefMut};
use super::Error;
use crate::Error::MalformedMetadata;
#[derive(Debug)]
pub struct | <'a>(HashMap<&'a str, &'a str>);
impl<'a> MetadataMap<'a> {
/// Returns a string that indicates the character set.
pub fn charset(&self) -> Option<&'a str> {
self.get("Content-Type")
.and_then(|x| x.split("charset=").nth(1))
}
/// Returns the number of different plurals and the boolean
/// expression to determine the form to use depending on
/// the number of elements.
///
/// Defaults to `n_plurals = 2` and `plural = n!=1` (as in English).
pub fn plural_forms(&self) -> (Option<usize>, Option<&'a str>) {
self.get("Plural-Forms")
.map(|f| {
f.split(';').fold((None, None), |(n_pl, pl), prop| {
match prop.chars().position(|c| c == '=') {
Some(index) => {
let (name, value) = prop.split_at(index);
let value = value[1..value.len()].trim();
match name.trim() {
"n_plurals" => (usize::from_str_radix(value, 10).ok(), pl),
"plural" => (n_pl, Some(value)),
_ => (n_pl, pl),
}
}
None => (n_pl, pl),
}
})
})
.unwrap_or((None, None))
}
}
impl<'a> Deref for MetadataMap<'a> {
type Target = HashMap<&'a str, &'a str>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<'a> DerefMut for MetadataMap<'a> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
pub fn parse_metadata(blob: &str) -> Result<MetadataMap, Error> {
let mut map = MetadataMap(HashMap::new());
for line in blob.split('\n').filter(|s| s!= &"") {
let pos = match line.bytes().position(|b| b == b':') {
Some(p) => p,
None => return Err(MalformedMetadata),
};
map.insert(line[..pos].trim(), line[pos + 1..].trim());
}
Ok(map)
}
#[test]
fn test_metadatamap_charset() {
{
let mut map = MetadataMap(HashMap::new());
assert!(map.charset().is_none());
map.insert("Content-Type", "");
assert!(map.charset().is_none());
map.insert("Content-Type", "abc");
assert!(map.charset().is_none());
map.insert("Content-Type", "text/plain; charset=utf-42");
assert_eq!(map.charset().unwrap(), "utf-42");
}
}
#[test]
fn test_metadatamap_plural() {
{
let mut map = MetadataMap(HashMap::new());
assert_eq!(map.plural_forms(), (None, None));
map.insert("Plural-Forms", "");
assert_eq!(map.plural_forms(), (None, None));
// n_plural
map.insert("Plural-Forms", "n_plurals=42");
assert_eq!(map.plural_forms(), (Some(42), None));
// plural is specified
map.insert("Plural-Forms", "n_plurals=2; plural=n==12");
assert_eq!(map.plural_forms(), (Some(2), Some("n==12")));
// plural before n_plurals
map.insert("Plural-Forms", "plural=n==12; n_plurals=2");
assert_eq!(map.plural_forms(), (Some(2), Some("n==12")));
// with spaces
map.insert("Plural-Forms", " n_plurals = 42 ; plural = n > 10 ");
assert_eq!(map.plural_forms(), (Some(42), Some("n > 10")));
}
}
| MetadataMap | identifier_name |
metadata.rs | use std::collections::HashMap;
use std::ops::{Deref, DerefMut};
use super::Error;
use crate::Error::MalformedMetadata;
#[derive(Debug)]
pub struct MetadataMap<'a>(HashMap<&'a str, &'a str>);
impl<'a> MetadataMap<'a> {
/// Returns a string that indicates the character set.
pub fn charset(&self) -> Option<&'a str> {
self.get("Content-Type")
.and_then(|x| x.split("charset=").nth(1))
}
/// Returns the number of different plurals and the boolean
/// expression to determine the form to use depending on
/// the number of elements.
///
/// Defaults to `n_plurals = 2` and `plural = n!=1` (as in English).
pub fn plural_forms(&self) -> (Option<usize>, Option<&'a str>) |
}
impl<'a> Deref for MetadataMap<'a> {
type Target = HashMap<&'a str, &'a str>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<'a> DerefMut for MetadataMap<'a> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
pub fn parse_metadata(blob: &str) -> Result<MetadataMap, Error> {
let mut map = MetadataMap(HashMap::new());
for line in blob.split('\n').filter(|s| s!= &"") {
let pos = match line.bytes().position(|b| b == b':') {
Some(p) => p,
None => return Err(MalformedMetadata),
};
map.insert(line[..pos].trim(), line[pos + 1..].trim());
}
Ok(map)
}
#[test]
fn test_metadatamap_charset() {
{
let mut map = MetadataMap(HashMap::new());
assert!(map.charset().is_none());
map.insert("Content-Type", "");
assert!(map.charset().is_none());
map.insert("Content-Type", "abc");
assert!(map.charset().is_none());
map.insert("Content-Type", "text/plain; charset=utf-42");
assert_eq!(map.charset().unwrap(), "utf-42");
}
}
#[test]
fn test_metadatamap_plural() {
{
let mut map = MetadataMap(HashMap::new());
assert_eq!(map.plural_forms(), (None, None));
map.insert("Plural-Forms", "");
assert_eq!(map.plural_forms(), (None, None));
// n_plural
map.insert("Plural-Forms", "n_plurals=42");
assert_eq!(map.plural_forms(), (Some(42), None));
// plural is specified
map.insert("Plural-Forms", "n_plurals=2; plural=n==12");
assert_eq!(map.plural_forms(), (Some(2), Some("n==12")));
// plural before n_plurals
map.insert("Plural-Forms", "plural=n==12; n_plurals=2");
assert_eq!(map.plural_forms(), (Some(2), Some("n==12")));
// with spaces
map.insert("Plural-Forms", " n_plurals = 42 ; plural = n > 10 ");
assert_eq!(map.plural_forms(), (Some(42), Some("n > 10")));
}
}
| {
self.get("Plural-Forms")
.map(|f| {
f.split(';').fold((None, None), |(n_pl, pl), prop| {
match prop.chars().position(|c| c == '=') {
Some(index) => {
let (name, value) = prop.split_at(index);
let value = value[1..value.len()].trim();
match name.trim() {
"n_plurals" => (usize::from_str_radix(value, 10).ok(), pl),
"plural" => (n_pl, Some(value)),
_ => (n_pl, pl),
}
}
None => (n_pl, pl),
}
})
})
.unwrap_or((None, None))
} | identifier_body |
ip.rs | use pktparse::{ipv4, ipv6};
use std::fmt::Display;
use std::net::Ipv4Addr;
pub trait IPHeader {
type Addr: Display;
fn source_addr(&self) -> Self::Addr;
fn dest_addr(&self) -> Self::Addr;
}
impl IPHeader for ipv4::IPv4Header {
type Addr = Ipv4Addr;
#[inline]
fn source_addr(&self) -> Self::Addr {
self.source_addr
}
#[inline]
fn | (&self) -> Self::Addr {
self.dest_addr
}
}
impl IPHeader for ipv6::IPv6Header {
type Addr = String;
#[inline]
fn source_addr(&self) -> Self::Addr {
format!("[{}]", self.source_addr)
}
#[inline]
fn dest_addr(&self) -> Self::Addr {
format!("[{}]", self.dest_addr)
}
}
| dest_addr | identifier_name |
ip.rs | use pktparse::{ipv4, ipv6}; |
fn source_addr(&self) -> Self::Addr;
fn dest_addr(&self) -> Self::Addr;
}
impl IPHeader for ipv4::IPv4Header {
type Addr = Ipv4Addr;
#[inline]
fn source_addr(&self) -> Self::Addr {
self.source_addr
}
#[inline]
fn dest_addr(&self) -> Self::Addr {
self.dest_addr
}
}
impl IPHeader for ipv6::IPv6Header {
type Addr = String;
#[inline]
fn source_addr(&self) -> Self::Addr {
format!("[{}]", self.source_addr)
}
#[inline]
fn dest_addr(&self) -> Self::Addr {
format!("[{}]", self.dest_addr)
}
} | use std::fmt::Display;
use std::net::Ipv4Addr;
pub trait IPHeader {
type Addr: Display; | random_line_split |
ip.rs | use pktparse::{ipv4, ipv6};
use std::fmt::Display;
use std::net::Ipv4Addr;
pub trait IPHeader {
type Addr: Display;
fn source_addr(&self) -> Self::Addr;
fn dest_addr(&self) -> Self::Addr;
}
impl IPHeader for ipv4::IPv4Header {
type Addr = Ipv4Addr;
#[inline]
fn source_addr(&self) -> Self::Addr {
self.source_addr
}
#[inline]
fn dest_addr(&self) -> Self::Addr {
self.dest_addr
}
}
impl IPHeader for ipv6::IPv6Header {
type Addr = String;
#[inline]
fn source_addr(&self) -> Self::Addr |
#[inline]
fn dest_addr(&self) -> Self::Addr {
format!("[{}]", self.dest_addr)
}
}
| {
format!("[{}]", self.source_addr)
} | identifier_body |
main.rs | fn main() | "May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"];
println!("Months of the year: {:?}", months);
} | {
let mut x = 5;
println!("The value of x is: {}", x);
x = 6;
println!("The value of x is: {}", x);
let x = x + 1;
let x = x * 2;
println!("The value of x is: {}", x);
let tup = (500, 6.4, 1);
let (x, y, z) = tup;
println!("The value of x is: {}", x);
println!("The value of y is: {}", y);
println!("The value of z is: {}", z);
let months = ["January",
"February",
"March",
"April", | identifier_body |
main.rs | fn | () {
let mut x = 5;
println!("The value of x is: {}", x);
x = 6;
println!("The value of x is: {}", x);
let x = x + 1;
let x = x * 2;
println!("The value of x is: {}", x);
let tup = (500, 6.4, 1);
let (x, y, z) = tup;
println!("The value of x is: {}", x);
println!("The value of y is: {}", y);
println!("The value of z is: {}", z);
let months = ["January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"];
println!("Months of the year: {:?}", months);
} | main | identifier_name |
main.rs | fn main() {
let mut x = 5;
println!("The value of x is: {}", x);
x = 6;
println!("The value of x is: {}", x);
let x = x + 1;
let x = x * 2;
println!("The value of x is: {}", x);
let tup = (500, 6.4, 1);
let (x, y, z) = tup;
println!("The value of x is: {}", x);
println!("The value of y is: {}", y);
println!("The value of z is: {}", z);
let months = ["January",
"February",
"March", | "June",
"July",
"August",
"September",
"October",
"November",
"December"];
println!("Months of the year: {:?}", months);
} | "April",
"May", | random_line_split |
expr-copy.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.
fn f(arg: &mut A) |
struct A { a: int }
pub fn main() {
let mut x = A {a: 10};
f(&mut x);
assert_eq!(x.a, 100);
x.a = 20;
let mut y = x;
f(&mut y);
assert_eq!(x.a, 20);
}
| {
arg.a = 100;
} | identifier_body |
expr-copy.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.
fn f(arg: &mut A) {
arg.a = 100;
}
| f(&mut x);
assert_eq!(x.a, 100);
x.a = 20;
let mut y = x;
f(&mut y);
assert_eq!(x.a, 20);
} | struct A { a: int }
pub fn main() {
let mut x = A {a: 10}; | random_line_split |
expr-copy.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.
fn f(arg: &mut A) {
arg.a = 100;
}
struct | { a: int }
pub fn main() {
let mut x = A {a: 10};
f(&mut x);
assert_eq!(x.a, 100);
x.a = 20;
let mut y = x;
f(&mut y);
assert_eq!(x.a, 20);
}
| A | identifier_name |
issue-3794.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.
#![allow(unknown_features)]
#![feature(box_syntax)]
trait T {
fn print(&self);
}
#[derive(Show)]
struct S {
s: int,
}
impl T for S {
fn print(&self) {
println!("{:?}", self);
}
}
fn print_t(t: &T) {
t.print();
}
fn print_s(s: &S) |
pub fn main() {
let s: Box<S> = box S { s: 5 };
print_s(&*s);
let t: Box<T> = s as Box<T>;
print_t(&*t);
}
| {
s.print();
} | identifier_body |
issue-3794.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.
#![allow(unknown_features)]
#![feature(box_syntax)]
trait T {
fn print(&self);
}
#[derive(Show)]
struct S {
s: int,
}
impl T for S {
fn print(&self) {
println!("{:?}", self);
}
}
| s.print();
}
pub fn main() {
let s: Box<S> = box S { s: 5 };
print_s(&*s);
let t: Box<T> = s as Box<T>;
print_t(&*t);
} | fn print_t(t: &T) {
t.print();
}
fn print_s(s: &S) { | random_line_split |
issue-3794.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.
#![allow(unknown_features)]
#![feature(box_syntax)]
trait T {
fn print(&self);
}
#[derive(Show)]
struct S {
s: int,
}
impl T for S {
fn print(&self) {
println!("{:?}", self);
}
}
fn print_t(t: &T) {
t.print();
}
fn | (s: &S) {
s.print();
}
pub fn main() {
let s: Box<S> = box S { s: 5 };
print_s(&*s);
let t: Box<T> = s as Box<T>;
print_t(&*t);
}
| print_s | identifier_name |
request.rs | //! Client Requests
use std::marker::PhantomData;
use std::io::{self, Write, BufWriter};
use std::net::Shutdown;
use url::Url;
use method::{self, Method};
use header::Headers;
use header::{self, Host};
use net::{NetworkStream, NetworkConnector, HttpConnector, Fresh, Streaming};
use http::{self, HttpWriter, LINE_ENDING};
use http::HttpWriter::{ThroughWriter, ChunkedWriter, SizedWriter, EmptyWriter};
use version;
use client::{Response, get_host_and_port};
/// A client request to a remote server.
pub struct Request<W> {
/// The target URI for this request.
pub url: Url,
/// The HTTP version of this request.
pub version: version::HttpVersion,
body: HttpWriter<BufWriter<Box<NetworkStream + Send>>>,
headers: Headers,
method: method::Method,
_marker: PhantomData<W>,
}
impl<W> Request<W> {
/// Read the Request headers.
#[inline]
pub fn headers(&self) -> &Headers { &self.headers }
/// Read the Request method.
#[inline]
pub fn method(&self) -> method::Method { self.method.clone() }
}
impl Request<Fresh> {
/// Create a new client request.
pub fn new(method: method::Method, url: Url) -> ::Result<Request<Fresh>> {
let mut conn = HttpConnector(None);
Request::with_connector(method, url, &mut conn)
}
/// Create a new client request with a specific underlying NetworkStream.
pub fn with_connector<C, S>(method: method::Method, url: Url, connector: &mut C)
-> ::Result<Request<Fresh>> where
C: NetworkConnector<Stream=S>,
S: Into<Box<NetworkStream + Send>> {
let (host, port) = try!(get_host_and_port(&url));
let stream = try!(connector.connect(&*host, port, &*url.scheme)).into();
let stream = ThroughWriter(BufWriter::new(stream));
let mut headers = Headers::new();
headers.set(Host {
hostname: host,
port: Some(port),
});
Ok(Request {
method: method,
headers: headers,
url: url,
version: version::HttpVersion::Http11,
body: stream,
_marker: PhantomData,
})
}
/// Consume a Fresh Request, writing the headers and method,
/// returning a Streaming Request.
pub fn start(mut self) -> ::Result<Request<Streaming>> {
let mut uri = self.url.serialize_path().unwrap();
//TODO: this needs a test
if let Some(ref q) = self.url.query {
uri.push('?');
uri.push_str(&q[..]);
}
debug!("request line: {:?} {:?} {:?}", self.method, uri, self.version);
try!(write!(&mut self.body, "{} {} {}{}",
self.method, uri, self.version, LINE_ENDING));
let stream = match self.method {
Method::Get | Method::Head => {
debug!("headers={:?}", self.headers);
try!(write!(&mut self.body, "{}{}", self.headers, LINE_ENDING));
EmptyWriter(self.body.into_inner())
},
_ => {
let mut chunked = true;
let mut len = 0;
match self.headers.get::<header::ContentLength>() {
Some(cl) => {
chunked = false;
len = **cl;
},
None => ()
};
// cant do in match above, thanks borrowck
if chunked {
let encodings = match self.headers.get_mut::<header::TransferEncoding>() {
Some(&mut header::TransferEncoding(ref mut encodings)) => {
//TODO: check if chunked is already in encodings. use HashSet?
encodings.push(header::Encoding::Chunked);
false
},
None => true
};
if encodings {
self.headers.set::<header::TransferEncoding>(
header::TransferEncoding(vec![header::Encoding::Chunked]))
}
}
debug!("headers={:?}", self.headers);
try!(write!(&mut self.body, "{}{}", self.headers, LINE_ENDING));
if chunked {
ChunkedWriter(self.body.into_inner())
} else {
SizedWriter(self.body.into_inner(), len)
}
}
};
Ok(Request {
method: self.method,
headers: self.headers,
url: self.url,
version: self.version,
body: stream,
_marker: PhantomData,
})
}
/// Get a mutable reference to the Request headers.
#[inline]
pub fn headers_mut(&mut self) -> &mut Headers |
}
impl Request<Streaming> {
/// Completes writing the request, and returns a response to read from.
///
/// Consumes the Request.
pub fn send(self) -> ::Result<Response> {
let mut raw = try!(self.body.end()).into_inner().unwrap(); // end() already flushes
if!http::should_keep_alive(self.version, &self.headers) {
try!(raw.close(Shutdown::Write));
}
Response::new(raw)
}
}
impl Write for Request<Streaming> {
#[inline]
fn write(&mut self, msg: &[u8]) -> io::Result<usize> {
self.body.write(msg)
}
#[inline]
fn flush(&mut self) -> io::Result<()> {
self.body.flush()
}
}
#[cfg(test)]
mod tests {
use std::str::from_utf8;
use url::Url;
use method::Method::{Get, Head};
use mock::{MockStream, MockConnector};
use super::Request;
#[test]
fn test_get_empty_body() {
let req = Request::with_connector(
Get, Url::parse("http://example.dom").unwrap(), &mut MockConnector
).unwrap();
let req = req.start().unwrap();
let stream = *req.body.end().unwrap()
.into_inner().unwrap().downcast::<MockStream>().ok().unwrap();
let bytes = stream.write;
let s = from_utf8(&bytes[..]).unwrap();
assert!(!s.contains("Content-Length:"));
assert!(!s.contains("Transfer-Encoding:"));
}
#[test]
fn test_head_empty_body() {
let req = Request::with_connector(
Head, Url::parse("http://example.dom").unwrap(), &mut MockConnector
).unwrap();
let req = req.start().unwrap();
let stream = *req.body.end().unwrap()
.into_inner().unwrap().downcast::<MockStream>().ok().unwrap();
let bytes = stream.write;
let s = from_utf8(&bytes[..]).unwrap();
assert!(!s.contains("Content-Length:"));
assert!(!s.contains("Transfer-Encoding:"));
}
}
| { &mut self.headers } | identifier_body |
request.rs | //! Client Requests
use std::marker::PhantomData;
use std::io::{self, Write, BufWriter};
use std::net::Shutdown;
use url::Url;
use method::{self, Method};
use header::Headers;
use header::{self, Host};
use net::{NetworkStream, NetworkConnector, HttpConnector, Fresh, Streaming};
use http::{self, HttpWriter, LINE_ENDING};
use http::HttpWriter::{ThroughWriter, ChunkedWriter, SizedWriter, EmptyWriter};
use version;
use client::{Response, get_host_and_port};
/// A client request to a remote server.
pub struct Request<W> {
/// The target URI for this request.
pub url: Url,
/// The HTTP version of this request.
pub version: version::HttpVersion,
body: HttpWriter<BufWriter<Box<NetworkStream + Send>>>,
headers: Headers,
method: method::Method,
_marker: PhantomData<W>,
}
impl<W> Request<W> {
/// Read the Request headers.
#[inline]
pub fn headers(&self) -> &Headers { &self.headers }
/// Read the Request method.
#[inline]
pub fn method(&self) -> method::Method { self.method.clone() }
}
impl Request<Fresh> {
/// Create a new client request.
pub fn new(method: method::Method, url: Url) -> ::Result<Request<Fresh>> {
let mut conn = HttpConnector(None);
Request::with_connector(method, url, &mut conn)
}
/// Create a new client request with a specific underlying NetworkStream.
pub fn with_connector<C, S>(method: method::Method, url: Url, connector: &mut C)
-> ::Result<Request<Fresh>> where
C: NetworkConnector<Stream=S>,
S: Into<Box<NetworkStream + Send>> {
let (host, port) = try!(get_host_and_port(&url));
let stream = try!(connector.connect(&*host, port, &*url.scheme)).into();
let stream = ThroughWriter(BufWriter::new(stream));
let mut headers = Headers::new();
headers.set(Host {
hostname: host,
port: Some(port),
});
Ok(Request {
method: method,
headers: headers,
url: url,
version: version::HttpVersion::Http11,
body: stream,
_marker: PhantomData,
})
}
/// Consume a Fresh Request, writing the headers and method,
/// returning a Streaming Request.
pub fn start(mut self) -> ::Result<Request<Streaming>> {
let mut uri = self.url.serialize_path().unwrap();
//TODO: this needs a test
if let Some(ref q) = self.url.query {
uri.push('?');
uri.push_str(&q[..]);
}
debug!("request line: {:?} {:?} {:?}", self.method, uri, self.version);
try!(write!(&mut self.body, "{} {} {}{}",
self.method, uri, self.version, LINE_ENDING));
let stream = match self.method {
Method::Get | Method::Head => {
debug!("headers={:?}", self.headers);
try!(write!(&mut self.body, "{}{}", self.headers, LINE_ENDING));
EmptyWriter(self.body.into_inner())
},
_ => {
let mut chunked = true;
let mut len = 0;
match self.headers.get::<header::ContentLength>() {
Some(cl) => {
chunked = false;
len = **cl;
},
None => ()
};
// cant do in match above, thanks borrowck
if chunked {
let encodings = match self.headers.get_mut::<header::TransferEncoding>() {
Some(&mut header::TransferEncoding(ref mut encodings)) => {
//TODO: check if chunked is already in encodings. use HashSet?
encodings.push(header::Encoding::Chunked);
false
},
None => true
};
if encodings {
self.headers.set::<header::TransferEncoding>(
header::TransferEncoding(vec![header::Encoding::Chunked]))
}
}
debug!("headers={:?}", self.headers);
try!(write!(&mut self.body, "{}{}", self.headers, LINE_ENDING));
if chunked {
ChunkedWriter(self.body.into_inner())
} else {
SizedWriter(self.body.into_inner(), len)
}
}
};
Ok(Request {
method: self.method,
headers: self.headers,
url: self.url,
version: self.version,
body: stream,
_marker: PhantomData,
})
}
/// Get a mutable reference to the Request headers.
#[inline]
pub fn headers_mut(&mut self) -> &mut Headers { &mut self.headers }
}
impl Request<Streaming> {
/// Completes writing the request, and returns a response to read from.
///
/// Consumes the Request.
pub fn send(self) -> ::Result<Response> {
let mut raw = try!(self.body.end()).into_inner().unwrap(); // end() already flushes
if!http::should_keep_alive(self.version, &self.headers) {
try!(raw.close(Shutdown::Write));
}
Response::new(raw)
}
}
impl Write for Request<Streaming> {
#[inline]
fn write(&mut self, msg: &[u8]) -> io::Result<usize> {
self.body.write(msg)
}
#[inline]
fn flush(&mut self) -> io::Result<()> {
self.body.flush()
}
}
#[cfg(test)]
mod tests {
use std::str::from_utf8;
use url::Url;
use method::Method::{Get, Head};
use mock::{MockStream, MockConnector};
use super::Request;
#[test]
fn test_get_empty_body() {
let req = Request::with_connector(
Get, Url::parse("http://example.dom").unwrap(), &mut MockConnector | .into_inner().unwrap().downcast::<MockStream>().ok().unwrap();
let bytes = stream.write;
let s = from_utf8(&bytes[..]).unwrap();
assert!(!s.contains("Content-Length:"));
assert!(!s.contains("Transfer-Encoding:"));
}
#[test]
fn test_head_empty_body() {
let req = Request::with_connector(
Head, Url::parse("http://example.dom").unwrap(), &mut MockConnector
).unwrap();
let req = req.start().unwrap();
let stream = *req.body.end().unwrap()
.into_inner().unwrap().downcast::<MockStream>().ok().unwrap();
let bytes = stream.write;
let s = from_utf8(&bytes[..]).unwrap();
assert!(!s.contains("Content-Length:"));
assert!(!s.contains("Transfer-Encoding:"));
}
} | ).unwrap();
let req = req.start().unwrap();
let stream = *req.body.end().unwrap() | random_line_split |
request.rs | //! Client Requests
use std::marker::PhantomData;
use std::io::{self, Write, BufWriter};
use std::net::Shutdown;
use url::Url;
use method::{self, Method};
use header::Headers;
use header::{self, Host};
use net::{NetworkStream, NetworkConnector, HttpConnector, Fresh, Streaming};
use http::{self, HttpWriter, LINE_ENDING};
use http::HttpWriter::{ThroughWriter, ChunkedWriter, SizedWriter, EmptyWriter};
use version;
use client::{Response, get_host_and_port};
/// A client request to a remote server.
pub struct Request<W> {
/// The target URI for this request.
pub url: Url,
/// The HTTP version of this request.
pub version: version::HttpVersion,
body: HttpWriter<BufWriter<Box<NetworkStream + Send>>>,
headers: Headers,
method: method::Method,
_marker: PhantomData<W>,
}
impl<W> Request<W> {
/// Read the Request headers.
#[inline]
pub fn headers(&self) -> &Headers { &self.headers }
/// Read the Request method.
#[inline]
pub fn | (&self) -> method::Method { self.method.clone() }
}
impl Request<Fresh> {
/// Create a new client request.
pub fn new(method: method::Method, url: Url) -> ::Result<Request<Fresh>> {
let mut conn = HttpConnector(None);
Request::with_connector(method, url, &mut conn)
}
/// Create a new client request with a specific underlying NetworkStream.
pub fn with_connector<C, S>(method: method::Method, url: Url, connector: &mut C)
-> ::Result<Request<Fresh>> where
C: NetworkConnector<Stream=S>,
S: Into<Box<NetworkStream + Send>> {
let (host, port) = try!(get_host_and_port(&url));
let stream = try!(connector.connect(&*host, port, &*url.scheme)).into();
let stream = ThroughWriter(BufWriter::new(stream));
let mut headers = Headers::new();
headers.set(Host {
hostname: host,
port: Some(port),
});
Ok(Request {
method: method,
headers: headers,
url: url,
version: version::HttpVersion::Http11,
body: stream,
_marker: PhantomData,
})
}
/// Consume a Fresh Request, writing the headers and method,
/// returning a Streaming Request.
pub fn start(mut self) -> ::Result<Request<Streaming>> {
let mut uri = self.url.serialize_path().unwrap();
//TODO: this needs a test
if let Some(ref q) = self.url.query {
uri.push('?');
uri.push_str(&q[..]);
}
debug!("request line: {:?} {:?} {:?}", self.method, uri, self.version);
try!(write!(&mut self.body, "{} {} {}{}",
self.method, uri, self.version, LINE_ENDING));
let stream = match self.method {
Method::Get | Method::Head => {
debug!("headers={:?}", self.headers);
try!(write!(&mut self.body, "{}{}", self.headers, LINE_ENDING));
EmptyWriter(self.body.into_inner())
},
_ => {
let mut chunked = true;
let mut len = 0;
match self.headers.get::<header::ContentLength>() {
Some(cl) => {
chunked = false;
len = **cl;
},
None => ()
};
// cant do in match above, thanks borrowck
if chunked {
let encodings = match self.headers.get_mut::<header::TransferEncoding>() {
Some(&mut header::TransferEncoding(ref mut encodings)) => {
//TODO: check if chunked is already in encodings. use HashSet?
encodings.push(header::Encoding::Chunked);
false
},
None => true
};
if encodings {
self.headers.set::<header::TransferEncoding>(
header::TransferEncoding(vec![header::Encoding::Chunked]))
}
}
debug!("headers={:?}", self.headers);
try!(write!(&mut self.body, "{}{}", self.headers, LINE_ENDING));
if chunked {
ChunkedWriter(self.body.into_inner())
} else {
SizedWriter(self.body.into_inner(), len)
}
}
};
Ok(Request {
method: self.method,
headers: self.headers,
url: self.url,
version: self.version,
body: stream,
_marker: PhantomData,
})
}
/// Get a mutable reference to the Request headers.
#[inline]
pub fn headers_mut(&mut self) -> &mut Headers { &mut self.headers }
}
impl Request<Streaming> {
/// Completes writing the request, and returns a response to read from.
///
/// Consumes the Request.
pub fn send(self) -> ::Result<Response> {
let mut raw = try!(self.body.end()).into_inner().unwrap(); // end() already flushes
if!http::should_keep_alive(self.version, &self.headers) {
try!(raw.close(Shutdown::Write));
}
Response::new(raw)
}
}
impl Write for Request<Streaming> {
#[inline]
fn write(&mut self, msg: &[u8]) -> io::Result<usize> {
self.body.write(msg)
}
#[inline]
fn flush(&mut self) -> io::Result<()> {
self.body.flush()
}
}
#[cfg(test)]
mod tests {
use std::str::from_utf8;
use url::Url;
use method::Method::{Get, Head};
use mock::{MockStream, MockConnector};
use super::Request;
#[test]
fn test_get_empty_body() {
let req = Request::with_connector(
Get, Url::parse("http://example.dom").unwrap(), &mut MockConnector
).unwrap();
let req = req.start().unwrap();
let stream = *req.body.end().unwrap()
.into_inner().unwrap().downcast::<MockStream>().ok().unwrap();
let bytes = stream.write;
let s = from_utf8(&bytes[..]).unwrap();
assert!(!s.contains("Content-Length:"));
assert!(!s.contains("Transfer-Encoding:"));
}
#[test]
fn test_head_empty_body() {
let req = Request::with_connector(
Head, Url::parse("http://example.dom").unwrap(), &mut MockConnector
).unwrap();
let req = req.start().unwrap();
let stream = *req.body.end().unwrap()
.into_inner().unwrap().downcast::<MockStream>().ok().unwrap();
let bytes = stream.write;
let s = from_utf8(&bytes[..]).unwrap();
assert!(!s.contains("Content-Length:"));
assert!(!s.contains("Transfer-Encoding:"));
}
}
| method | identifier_name |
request.rs | //! Client Requests
use std::marker::PhantomData;
use std::io::{self, Write, BufWriter};
use std::net::Shutdown;
use url::Url;
use method::{self, Method};
use header::Headers;
use header::{self, Host};
use net::{NetworkStream, NetworkConnector, HttpConnector, Fresh, Streaming};
use http::{self, HttpWriter, LINE_ENDING};
use http::HttpWriter::{ThroughWriter, ChunkedWriter, SizedWriter, EmptyWriter};
use version;
use client::{Response, get_host_and_port};
/// A client request to a remote server.
pub struct Request<W> {
/// The target URI for this request.
pub url: Url,
/// The HTTP version of this request.
pub version: version::HttpVersion,
body: HttpWriter<BufWriter<Box<NetworkStream + Send>>>,
headers: Headers,
method: method::Method,
_marker: PhantomData<W>,
}
impl<W> Request<W> {
/// Read the Request headers.
#[inline]
pub fn headers(&self) -> &Headers { &self.headers }
/// Read the Request method.
#[inline]
pub fn method(&self) -> method::Method { self.method.clone() }
}
impl Request<Fresh> {
/// Create a new client request.
pub fn new(method: method::Method, url: Url) -> ::Result<Request<Fresh>> {
let mut conn = HttpConnector(None);
Request::with_connector(method, url, &mut conn)
}
/// Create a new client request with a specific underlying NetworkStream.
pub fn with_connector<C, S>(method: method::Method, url: Url, connector: &mut C)
-> ::Result<Request<Fresh>> where
C: NetworkConnector<Stream=S>,
S: Into<Box<NetworkStream + Send>> {
let (host, port) = try!(get_host_and_port(&url));
let stream = try!(connector.connect(&*host, port, &*url.scheme)).into();
let stream = ThroughWriter(BufWriter::new(stream));
let mut headers = Headers::new();
headers.set(Host {
hostname: host,
port: Some(port),
});
Ok(Request {
method: method,
headers: headers,
url: url,
version: version::HttpVersion::Http11,
body: stream,
_marker: PhantomData,
})
}
/// Consume a Fresh Request, writing the headers and method,
/// returning a Streaming Request.
pub fn start(mut self) -> ::Result<Request<Streaming>> {
let mut uri = self.url.serialize_path().unwrap();
//TODO: this needs a test
if let Some(ref q) = self.url.query |
debug!("request line: {:?} {:?} {:?}", self.method, uri, self.version);
try!(write!(&mut self.body, "{} {} {}{}",
self.method, uri, self.version, LINE_ENDING));
let stream = match self.method {
Method::Get | Method::Head => {
debug!("headers={:?}", self.headers);
try!(write!(&mut self.body, "{}{}", self.headers, LINE_ENDING));
EmptyWriter(self.body.into_inner())
},
_ => {
let mut chunked = true;
let mut len = 0;
match self.headers.get::<header::ContentLength>() {
Some(cl) => {
chunked = false;
len = **cl;
},
None => ()
};
// cant do in match above, thanks borrowck
if chunked {
let encodings = match self.headers.get_mut::<header::TransferEncoding>() {
Some(&mut header::TransferEncoding(ref mut encodings)) => {
//TODO: check if chunked is already in encodings. use HashSet?
encodings.push(header::Encoding::Chunked);
false
},
None => true
};
if encodings {
self.headers.set::<header::TransferEncoding>(
header::TransferEncoding(vec![header::Encoding::Chunked]))
}
}
debug!("headers={:?}", self.headers);
try!(write!(&mut self.body, "{}{}", self.headers, LINE_ENDING));
if chunked {
ChunkedWriter(self.body.into_inner())
} else {
SizedWriter(self.body.into_inner(), len)
}
}
};
Ok(Request {
method: self.method,
headers: self.headers,
url: self.url,
version: self.version,
body: stream,
_marker: PhantomData,
})
}
/// Get a mutable reference to the Request headers.
#[inline]
pub fn headers_mut(&mut self) -> &mut Headers { &mut self.headers }
}
impl Request<Streaming> {
/// Completes writing the request, and returns a response to read from.
///
/// Consumes the Request.
pub fn send(self) -> ::Result<Response> {
let mut raw = try!(self.body.end()).into_inner().unwrap(); // end() already flushes
if!http::should_keep_alive(self.version, &self.headers) {
try!(raw.close(Shutdown::Write));
}
Response::new(raw)
}
}
impl Write for Request<Streaming> {
#[inline]
fn write(&mut self, msg: &[u8]) -> io::Result<usize> {
self.body.write(msg)
}
#[inline]
fn flush(&mut self) -> io::Result<()> {
self.body.flush()
}
}
#[cfg(test)]
mod tests {
use std::str::from_utf8;
use url::Url;
use method::Method::{Get, Head};
use mock::{MockStream, MockConnector};
use super::Request;
#[test]
fn test_get_empty_body() {
let req = Request::with_connector(
Get, Url::parse("http://example.dom").unwrap(), &mut MockConnector
).unwrap();
let req = req.start().unwrap();
let stream = *req.body.end().unwrap()
.into_inner().unwrap().downcast::<MockStream>().ok().unwrap();
let bytes = stream.write;
let s = from_utf8(&bytes[..]).unwrap();
assert!(!s.contains("Content-Length:"));
assert!(!s.contains("Transfer-Encoding:"));
}
#[test]
fn test_head_empty_body() {
let req = Request::with_connector(
Head, Url::parse("http://example.dom").unwrap(), &mut MockConnector
).unwrap();
let req = req.start().unwrap();
let stream = *req.body.end().unwrap()
.into_inner().unwrap().downcast::<MockStream>().ok().unwrap();
let bytes = stream.write;
let s = from_utf8(&bytes[..]).unwrap();
assert!(!s.contains("Content-Length:"));
assert!(!s.contains("Transfer-Encoding:"));
}
}
| {
uri.push('?');
uri.push_str(&q[..]);
} | conditional_block |
png2icns.rs | //! Creates an ICNS file containing a single image, read from a PNG file.
//!
//! To create an ICNS file from a PNG, run:
//!
//! ```shell
//! cargo run --example png2icns <path/to/file.png>
//! # ICNS will be saved to path/to/file.icns
//! ```
//!
//! Note that the dimensions of the input image must be exactly those of one of
//! the supported icon types (for example, 32x32 or 128x128).
//!
//! To create an ICNS file from a PNG using a specific icon type within the
//! ICNS file, run:
//!
//! ```shell
//! cargo run --example png2icns <path/to/file.png> <ostype>
//! # ICNS will be saved to path/to/file.<ostype>.icns
//! ```
//!
//! Where <ostype> is the OSType for the icon type you want to encode in. In
//! this case, the dimensions of the input image must match the particular
//! chosen icon type.
extern crate icns;
use icns::{IconFamily, IconType, Image, OSType};
use std::env;
use std::fs::File;
use std::io::{BufReader, BufWriter};
use std::path::Path;
use std::str::FromStr;
fn | () {
let num_args = env::args().count();
if num_args < 2 || num_args > 3 {
println!("Usage: png2icns <path> [<ostype>]");
return;
}
let png_path = env::args().nth(1).unwrap();
let png_path = Path::new(&png_path);
let png_file = BufReader::new(File::open(png_path)
.expect("failed to open PNG file"));
let image = Image::read_png(png_file).expect("failed to read PNG file");
let mut family = IconFamily::new();
let icns_path = if num_args == 3 {
let ostype = OSType::from_str(&env::args().nth(2).unwrap()).unwrap();
let icon_type = IconType::from_ostype(ostype)
.expect("unsupported ostype");
family.add_icon_with_type(&image, icon_type)
.expect("failed to encode image");
png_path.with_extension(format!("{}.icns", ostype))
} else {
family.add_icon(&image).expect("failed to encode image");
png_path.with_extension("icns")
};
let icns_file = BufWriter::new(File::create(icns_path)
.expect("failed to create ICNS file"));
family.write(icns_file).expect("failed to write ICNS file");
}
| main | identifier_name |
png2icns.rs | //! Creates an ICNS file containing a single image, read from a PNG file.
//!
//! To create an ICNS file from a PNG, run:
//!
//! ```shell
//! cargo run --example png2icns <path/to/file.png>
//! # ICNS will be saved to path/to/file.icns
//! ```
//!
//! Note that the dimensions of the input image must be exactly those of one of
//! the supported icon types (for example, 32x32 or 128x128).
//!
//! To create an ICNS file from a PNG using a specific icon type within the
//! ICNS file, run:
//!
//! ```shell
//! cargo run --example png2icns <path/to/file.png> <ostype>
//! # ICNS will be saved to path/to/file.<ostype>.icns
//! ```
//!
//! Where <ostype> is the OSType for the icon type you want to encode in. In
//! this case, the dimensions of the input image must match the particular
//! chosen icon type.
extern crate icns;
use icns::{IconFamily, IconType, Image, OSType};
use std::env;
use std::fs::File;
use std::io::{BufReader, BufWriter};
use std::path::Path;
use std::str::FromStr;
fn main() {
let num_args = env::args().count();
if num_args < 2 || num_args > 3 {
println!("Usage: png2icns <path> [<ostype>]");
return;
}
let png_path = env::args().nth(1).unwrap();
let png_path = Path::new(&png_path);
let png_file = BufReader::new(File::open(png_path)
.expect("failed to open PNG file"));
let image = Image::read_png(png_file).expect("failed to read PNG file");
let mut family = IconFamily::new();
let icns_path = if num_args == 3 {
let ostype = OSType::from_str(&env::args().nth(2).unwrap()).unwrap();
let icon_type = IconType::from_ostype(ostype)
.expect("unsupported ostype");
family.add_icon_with_type(&image, icon_type)
.expect("failed to encode image"); | png_path.with_extension("icns")
};
let icns_file = BufWriter::new(File::create(icns_path)
.expect("failed to create ICNS file"));
family.write(icns_file).expect("failed to write ICNS file");
} | png_path.with_extension(format!("{}.icns", ostype))
} else {
family.add_icon(&image).expect("failed to encode image"); | random_line_split |
png2icns.rs | //! Creates an ICNS file containing a single image, read from a PNG file.
//!
//! To create an ICNS file from a PNG, run:
//!
//! ```shell
//! cargo run --example png2icns <path/to/file.png>
//! # ICNS will be saved to path/to/file.icns
//! ```
//!
//! Note that the dimensions of the input image must be exactly those of one of
//! the supported icon types (for example, 32x32 or 128x128).
//!
//! To create an ICNS file from a PNG using a specific icon type within the
//! ICNS file, run:
//!
//! ```shell
//! cargo run --example png2icns <path/to/file.png> <ostype>
//! # ICNS will be saved to path/to/file.<ostype>.icns
//! ```
//!
//! Where <ostype> is the OSType for the icon type you want to encode in. In
//! this case, the dimensions of the input image must match the particular
//! chosen icon type.
extern crate icns;
use icns::{IconFamily, IconType, Image, OSType};
use std::env;
use std::fs::File;
use std::io::{BufReader, BufWriter};
use std::path::Path;
use std::str::FromStr;
fn main() {
let num_args = env::args().count();
if num_args < 2 || num_args > 3 |
let png_path = env::args().nth(1).unwrap();
let png_path = Path::new(&png_path);
let png_file = BufReader::new(File::open(png_path)
.expect("failed to open PNG file"));
let image = Image::read_png(png_file).expect("failed to read PNG file");
let mut family = IconFamily::new();
let icns_path = if num_args == 3 {
let ostype = OSType::from_str(&env::args().nth(2).unwrap()).unwrap();
let icon_type = IconType::from_ostype(ostype)
.expect("unsupported ostype");
family.add_icon_with_type(&image, icon_type)
.expect("failed to encode image");
png_path.with_extension(format!("{}.icns", ostype))
} else {
family.add_icon(&image).expect("failed to encode image");
png_path.with_extension("icns")
};
let icns_file = BufWriter::new(File::create(icns_path)
.expect("failed to create ICNS file"));
family.write(icns_file).expect("failed to write ICNS file");
}
| {
println!("Usage: png2icns <path> [<ostype>]");
return;
} | conditional_block |
png2icns.rs | //! Creates an ICNS file containing a single image, read from a PNG file.
//!
//! To create an ICNS file from a PNG, run:
//!
//! ```shell
//! cargo run --example png2icns <path/to/file.png>
//! # ICNS will be saved to path/to/file.icns
//! ```
//!
//! Note that the dimensions of the input image must be exactly those of one of
//! the supported icon types (for example, 32x32 or 128x128).
//!
//! To create an ICNS file from a PNG using a specific icon type within the
//! ICNS file, run:
//!
//! ```shell
//! cargo run --example png2icns <path/to/file.png> <ostype>
//! # ICNS will be saved to path/to/file.<ostype>.icns
//! ```
//!
//! Where <ostype> is the OSType for the icon type you want to encode in. In
//! this case, the dimensions of the input image must match the particular
//! chosen icon type.
extern crate icns;
use icns::{IconFamily, IconType, Image, OSType};
use std::env;
use std::fs::File;
use std::io::{BufReader, BufWriter};
use std::path::Path;
use std::str::FromStr;
fn main() | family.add_icon(&image).expect("failed to encode image");
png_path.with_extension("icns")
};
let icns_file = BufWriter::new(File::create(icns_path)
.expect("failed to create ICNS file"));
family.write(icns_file).expect("failed to write ICNS file");
}
| {
let num_args = env::args().count();
if num_args < 2 || num_args > 3 {
println!("Usage: png2icns <path> [<ostype>]");
return;
}
let png_path = env::args().nth(1).unwrap();
let png_path = Path::new(&png_path);
let png_file = BufReader::new(File::open(png_path)
.expect("failed to open PNG file"));
let image = Image::read_png(png_file).expect("failed to read PNG file");
let mut family = IconFamily::new();
let icns_path = if num_args == 3 {
let ostype = OSType::from_str(&env::args().nth(2).unwrap()).unwrap();
let icon_type = IconType::from_ostype(ostype)
.expect("unsupported ostype");
family.add_icon_with_type(&image, icon_type)
.expect("failed to encode image");
png_path.with_extension(format!("{}.icns", ostype))
} else { | identifier_body |
margin.mako.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 https://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% from data import DEFAULT_RULES_AND_PAGE %>
${helpers.four_sides_shorthand(
"margin",
"margin-%s",
"specified::LengthPercentageOrAuto::parse",
engines="gecko servo-2013 servo-2020",
spec="https://drafts.csswg.org/css-box/#propdef-margin",
rule_types_allowed=DEFAULT_RULES_AND_PAGE,
allow_quirks="Yes",
)}
${helpers.two_properties_shorthand(
"margin-block",
"margin-block-start",
"margin-block-end",
"specified::LengthPercentageOrAuto::parse",
engines="gecko servo-2013 servo-2020",
spec="https://drafts.csswg.org/css-logical/#propdef-margin-block"
)}
${helpers.two_properties_shorthand(
"margin-inline",
"margin-inline-start",
"margin-inline-end",
"specified::LengthPercentageOrAuto::parse",
engines="gecko servo-2013 servo-2020",
spec="https://drafts.csswg.org/css-logical/#propdef-margin-inline"
)}
| "scroll-margin",
"scroll-margin-%s",
"specified::Length::parse",
engines="gecko",
spec="https://drafts.csswg.org/css-scroll-snap-1/#propdef-scroll-margin",
)}
${helpers.two_properties_shorthand(
"scroll-margin-block",
"scroll-margin-block-start",
"scroll-margin-block-end",
"specified::Length::parse",
engines="gecko",
spec="https://drafts.csswg.org/css-scroll-snap-1/#propdef-scroll-margin-block",
)}
${helpers.two_properties_shorthand(
"scroll-margin-inline",
"scroll-margin-inline-start",
"scroll-margin-inline-end",
"specified::Length::parse",
engines="gecko",
spec="https://drafts.csswg.org/css-scroll-snap-1/#propdef-scroll-margin-inline",
)} | ${helpers.four_sides_shorthand( | random_line_split |
animation.rs | extern crate sdl2;
use std::path::Path;
use sdl2::event::Event;
use sdl2::keyboard::Keycode;
use sdl2::rect::Point;
use sdl2::rect::Rect;
use std::time::Duration;
fn | () -> Result<(), String> {
let sdl_context = sdl2::init()?;
let video_subsystem = sdl_context.video()?;
let window = video_subsystem
.window("SDL2", 640, 480)
.position_centered()
.build()
.map_err(|e| e.to_string())?;
let mut canvas = window
.into_canvas()
.accelerated()
.build()
.map_err(|e| e.to_string())?;
let texture_creator = canvas.texture_creator();
canvas.set_draw_color(sdl2::pixels::Color::RGBA(0, 0, 0, 255));
let timer = sdl_context.timer()?;
let mut event_pump = sdl_context.event_pump()?;
// animation sheet and extras are available from
// https://opengameart.org/content/a-platformer-in-the-forest
let temp_surface = sdl2::surface::Surface::load_bmp(Path::new("assets/characters.bmp"))?;
let texture = texture_creator
.create_texture_from_surface(&temp_surface)
.map_err(|e| e.to_string())?;
let frames_per_anim = 4;
let sprite_tile_size = (32, 32);
// Baby - walk animation
let mut source_rect_0 = Rect::new(0, 0, sprite_tile_size.0, sprite_tile_size.0);
let mut dest_rect_0 = Rect::new(0, 0, sprite_tile_size.0 * 4, sprite_tile_size.0 * 4);
dest_rect_0.center_on(Point::new(-64, 120));
// King - walk animation
let mut source_rect_1 = Rect::new(0, 32, sprite_tile_size.0, sprite_tile_size.0);
let mut dest_rect_1 = Rect::new(0, 32, sprite_tile_size.0 * 4, sprite_tile_size.0 * 4);
dest_rect_1.center_on(Point::new(0, 240));
// Soldier - walk animation
let mut source_rect_2 = Rect::new(0, 64, sprite_tile_size.0, sprite_tile_size.0);
let mut dest_rect_2 = Rect::new(0, 64, sprite_tile_size.0 * 4, sprite_tile_size.0 * 4);
dest_rect_2.center_on(Point::new(440, 360));
let mut running = true;
while running {
for event in event_pump.poll_iter() {
match event {
Event::Quit {.. }
| Event::KeyDown {
keycode: Some(Keycode::Escape),
..
} => {
running = false;
}
_ => {}
}
}
let ticks = timer.ticks() as i32;
// set the current frame for time
source_rect_0.set_x(32 * ((ticks / 100) % frames_per_anim));
dest_rect_0.set_x(1 * ((ticks / 14) % 768) - 128);
source_rect_1.set_x(32 * ((ticks / 100) % frames_per_anim));
dest_rect_1.set_x((1 * ((ticks / 12) % 768) - 672) * -1);
source_rect_2.set_x(32 * ((ticks / 100) % frames_per_anim));
dest_rect_2.set_x(1 * ((ticks / 10) % 768) - 128);
canvas.clear();
// copy the frame to the canvas
canvas.copy_ex(
&texture,
Some(source_rect_0),
Some(dest_rect_0),
0.0,
None,
false,
false,
)?;
canvas.copy_ex(
&texture,
Some(source_rect_1),
Some(dest_rect_1),
0.0,
None,
true,
false,
)?;
canvas.copy_ex(
&texture,
Some(source_rect_2),
Some(dest_rect_2),
0.0,
None,
false,
false,
)?;
canvas.present();
std::thread::sleep(Duration::from_millis(100));
}
Ok(())
}
| main | identifier_name |
animation.rs | extern crate sdl2;
use std::path::Path;
use sdl2::event::Event;
use sdl2::keyboard::Keycode;
use sdl2::rect::Point;
use sdl2::rect::Rect;
use std::time::Duration;
fn main() -> Result<(), String> {
let sdl_context = sdl2::init()?;
let video_subsystem = sdl_context.video()?;
let window = video_subsystem
.window("SDL2", 640, 480)
.position_centered()
.build()
.map_err(|e| e.to_string())?;
let mut canvas = window
.into_canvas()
.accelerated()
.build()
.map_err(|e| e.to_string())?;
let texture_creator = canvas.texture_creator();
canvas.set_draw_color(sdl2::pixels::Color::RGBA(0, 0, 0, 255));
let timer = sdl_context.timer()?;
let mut event_pump = sdl_context.event_pump()?;
// animation sheet and extras are available from
// https://opengameart.org/content/a-platformer-in-the-forest
let temp_surface = sdl2::surface::Surface::load_bmp(Path::new("assets/characters.bmp"))?;
let texture = texture_creator
.create_texture_from_surface(&temp_surface)
.map_err(|e| e.to_string())?;
let frames_per_anim = 4;
let sprite_tile_size = (32, 32);
// Baby - walk animation
let mut source_rect_0 = Rect::new(0, 0, sprite_tile_size.0, sprite_tile_size.0);
let mut dest_rect_0 = Rect::new(0, 0, sprite_tile_size.0 * 4, sprite_tile_size.0 * 4);
dest_rect_0.center_on(Point::new(-64, 120));
// King - walk animation
let mut source_rect_1 = Rect::new(0, 32, sprite_tile_size.0, sprite_tile_size.0); |
// Soldier - walk animation
let mut source_rect_2 = Rect::new(0, 64, sprite_tile_size.0, sprite_tile_size.0);
let mut dest_rect_2 = Rect::new(0, 64, sprite_tile_size.0 * 4, sprite_tile_size.0 * 4);
dest_rect_2.center_on(Point::new(440, 360));
let mut running = true;
while running {
for event in event_pump.poll_iter() {
match event {
Event::Quit {.. }
| Event::KeyDown {
keycode: Some(Keycode::Escape),
..
} => {
running = false;
}
_ => {}
}
}
let ticks = timer.ticks() as i32;
// set the current frame for time
source_rect_0.set_x(32 * ((ticks / 100) % frames_per_anim));
dest_rect_0.set_x(1 * ((ticks / 14) % 768) - 128);
source_rect_1.set_x(32 * ((ticks / 100) % frames_per_anim));
dest_rect_1.set_x((1 * ((ticks / 12) % 768) - 672) * -1);
source_rect_2.set_x(32 * ((ticks / 100) % frames_per_anim));
dest_rect_2.set_x(1 * ((ticks / 10) % 768) - 128);
canvas.clear();
// copy the frame to the canvas
canvas.copy_ex(
&texture,
Some(source_rect_0),
Some(dest_rect_0),
0.0,
None,
false,
false,
)?;
canvas.copy_ex(
&texture,
Some(source_rect_1),
Some(dest_rect_1),
0.0,
None,
true,
false,
)?;
canvas.copy_ex(
&texture,
Some(source_rect_2),
Some(dest_rect_2),
0.0,
None,
false,
false,
)?;
canvas.present();
std::thread::sleep(Duration::from_millis(100));
}
Ok(())
} | let mut dest_rect_1 = Rect::new(0, 32, sprite_tile_size.0 * 4, sprite_tile_size.0 * 4);
dest_rect_1.center_on(Point::new(0, 240)); | random_line_split |
animation.rs | extern crate sdl2;
use std::path::Path;
use sdl2::event::Event;
use sdl2::keyboard::Keycode;
use sdl2::rect::Point;
use sdl2::rect::Rect;
use std::time::Duration;
fn main() -> Result<(), String> |
let mut event_pump = sdl_context.event_pump()?;
// animation sheet and extras are available from
// https://opengameart.org/content/a-platformer-in-the-forest
let temp_surface = sdl2::surface::Surface::load_bmp(Path::new("assets/characters.bmp"))?;
let texture = texture_creator
.create_texture_from_surface(&temp_surface)
.map_err(|e| e.to_string())?;
let frames_per_anim = 4;
let sprite_tile_size = (32, 32);
// Baby - walk animation
let mut source_rect_0 = Rect::new(0, 0, sprite_tile_size.0, sprite_tile_size.0);
let mut dest_rect_0 = Rect::new(0, 0, sprite_tile_size.0 * 4, sprite_tile_size.0 * 4);
dest_rect_0.center_on(Point::new(-64, 120));
// King - walk animation
let mut source_rect_1 = Rect::new(0, 32, sprite_tile_size.0, sprite_tile_size.0);
let mut dest_rect_1 = Rect::new(0, 32, sprite_tile_size.0 * 4, sprite_tile_size.0 * 4);
dest_rect_1.center_on(Point::new(0, 240));
// Soldier - walk animation
let mut source_rect_2 = Rect::new(0, 64, sprite_tile_size.0, sprite_tile_size.0);
let mut dest_rect_2 = Rect::new(0, 64, sprite_tile_size.0 * 4, sprite_tile_size.0 * 4);
dest_rect_2.center_on(Point::new(440, 360));
let mut running = true;
while running {
for event in event_pump.poll_iter() {
match event {
Event::Quit {.. }
| Event::KeyDown {
keycode: Some(Keycode::Escape),
..
} => {
running = false;
}
_ => {}
}
}
let ticks = timer.ticks() as i32;
// set the current frame for time
source_rect_0.set_x(32 * ((ticks / 100) % frames_per_anim));
dest_rect_0.set_x(1 * ((ticks / 14) % 768) - 128);
source_rect_1.set_x(32 * ((ticks / 100) % frames_per_anim));
dest_rect_1.set_x((1 * ((ticks / 12) % 768) - 672) * -1);
source_rect_2.set_x(32 * ((ticks / 100) % frames_per_anim));
dest_rect_2.set_x(1 * ((ticks / 10) % 768) - 128);
canvas.clear();
// copy the frame to the canvas
canvas.copy_ex(
&texture,
Some(source_rect_0),
Some(dest_rect_0),
0.0,
None,
false,
false,
)?;
canvas.copy_ex(
&texture,
Some(source_rect_1),
Some(dest_rect_1),
0.0,
None,
true,
false,
)?;
canvas.copy_ex(
&texture,
Some(source_rect_2),
Some(dest_rect_2),
0.0,
None,
false,
false,
)?;
canvas.present();
std::thread::sleep(Duration::from_millis(100));
}
Ok(())
}
| {
let sdl_context = sdl2::init()?;
let video_subsystem = sdl_context.video()?;
let window = video_subsystem
.window("SDL2", 640, 480)
.position_centered()
.build()
.map_err(|e| e.to_string())?;
let mut canvas = window
.into_canvas()
.accelerated()
.build()
.map_err(|e| e.to_string())?;
let texture_creator = canvas.texture_creator();
canvas.set_draw_color(sdl2::pixels::Color::RGBA(0, 0, 0, 255));
let timer = sdl_context.timer()?; | identifier_body |
match-pipe-binding.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.
fn test1() {
// from issue 6338
match ((1, "a".to_string()), (2, "b".to_string())) {
((1, a), (2, b)) | ((2, b), (1, a)) => {
assert_eq!(a, "a".to_string());
assert_eq!(b, "b".to_string());
},
_ => panic!(),
}
}
fn test2() {
match (1, 2, 3) {
(1, a, b) | (2, b, a) => {
assert_eq!(a, 2);
assert_eq!(b, 3);
},
_ => panic!(),
}
}
fn test3() {
match (1, 2, 3) { | assert_eq!(*b, 3);
},
_ => panic!(),
}
}
fn test4() {
match (1, 2, 3) {
(1, a, b) | (2, b, a) if a == 2 => {
assert_eq!(a, 2);
assert_eq!(b, 3);
},
_ => panic!(),
}
}
fn test5() {
match (1, 2, 3) {
(1, ref a, ref b) | (2, ref b, ref a) if *a == 2 => {
assert_eq!(*a, 2);
assert_eq!(*b, 3);
},
_ => panic!(),
}
}
pub fn main() {
test1();
test2();
test3();
test4();
test5();
} | (1, ref a, ref b) | (2, ref b, ref a) => {
assert_eq!(*a, 2); | random_line_split |
match-pipe-binding.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.
fn test1() {
// from issue 6338
match ((1, "a".to_string()), (2, "b".to_string())) {
((1, a), (2, b)) | ((2, b), (1, a)) => {
assert_eq!(a, "a".to_string());
assert_eq!(b, "b".to_string());
},
_ => panic!(),
}
}
fn test2() {
match (1, 2, 3) {
(1, a, b) | (2, b, a) => {
assert_eq!(a, 2);
assert_eq!(b, 3);
},
_ => panic!(),
}
}
fn test3() {
match (1, 2, 3) {
(1, ref a, ref b) | (2, ref b, ref a) => {
assert_eq!(*a, 2);
assert_eq!(*b, 3);
},
_ => panic!(),
}
}
fn test4() {
match (1, 2, 3) {
(1, a, b) | (2, b, a) if a == 2 => {
assert_eq!(a, 2);
assert_eq!(b, 3);
},
_ => panic!(),
}
}
fn test5() {
match (1, 2, 3) {
(1, ref a, ref b) | (2, ref b, ref a) if *a == 2 => | ,
_ => panic!(),
}
}
pub fn main() {
test1();
test2();
test3();
test4();
test5();
}
| {
assert_eq!(*a, 2);
assert_eq!(*b, 3);
} | conditional_block |
match-pipe-binding.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.
fn | () {
// from issue 6338
match ((1, "a".to_string()), (2, "b".to_string())) {
((1, a), (2, b)) | ((2, b), (1, a)) => {
assert_eq!(a, "a".to_string());
assert_eq!(b, "b".to_string());
},
_ => panic!(),
}
}
fn test2() {
match (1, 2, 3) {
(1, a, b) | (2, b, a) => {
assert_eq!(a, 2);
assert_eq!(b, 3);
},
_ => panic!(),
}
}
fn test3() {
match (1, 2, 3) {
(1, ref a, ref b) | (2, ref b, ref a) => {
assert_eq!(*a, 2);
assert_eq!(*b, 3);
},
_ => panic!(),
}
}
fn test4() {
match (1, 2, 3) {
(1, a, b) | (2, b, a) if a == 2 => {
assert_eq!(a, 2);
assert_eq!(b, 3);
},
_ => panic!(),
}
}
fn test5() {
match (1, 2, 3) {
(1, ref a, ref b) | (2, ref b, ref a) if *a == 2 => {
assert_eq!(*a, 2);
assert_eq!(*b, 3);
},
_ => panic!(),
}
}
pub fn main() {
test1();
test2();
test3();
test4();
test5();
}
| test1 | identifier_name |
match-pipe-binding.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.
fn test1() {
// from issue 6338
match ((1, "a".to_string()), (2, "b".to_string())) {
((1, a), (2, b)) | ((2, b), (1, a)) => {
assert_eq!(a, "a".to_string());
assert_eq!(b, "b".to_string());
},
_ => panic!(),
}
}
fn test2() |
fn test3() {
match (1, 2, 3) {
(1, ref a, ref b) | (2, ref b, ref a) => {
assert_eq!(*a, 2);
assert_eq!(*b, 3);
},
_ => panic!(),
}
}
fn test4() {
match (1, 2, 3) {
(1, a, b) | (2, b, a) if a == 2 => {
assert_eq!(a, 2);
assert_eq!(b, 3);
},
_ => panic!(),
}
}
fn test5() {
match (1, 2, 3) {
(1, ref a, ref b) | (2, ref b, ref a) if *a == 2 => {
assert_eq!(*a, 2);
assert_eq!(*b, 3);
},
_ => panic!(),
}
}
pub fn main() {
test1();
test2();
test3();
test4();
test5();
}
| {
match (1, 2, 3) {
(1, a, b) | (2, b, a) => {
assert_eq!(a, 2);
assert_eq!(b, 3);
},
_ => panic!(),
}
} | identifier_body |
traits.rs | // Copyright 2015 The Ramp 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
// | // 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 module holds various traits.
/// A trait for types which can compute division and remainder in one step.
pub trait DivRem<RHS = Self> {
// Default to (Self, RHS) when associated type defaults are more stable.
type Output;
fn divrem(self, rhs: RHS) -> Self::Output;
}
/// We re-export num_integer::Integer for convenience.
pub use num_integer::Integer; | // http://www.apache.org/licenses/LICENSE-2.0
// | random_line_split |
states.rs | use std::{cell::RefCell, rc::Rc};
use stdweb::web::event;
/// Used to store and read web events.
pub struct | {
pub mouse_move_events: Rc<RefCell<Vec<event::MouseMoveEvent>>>,
pub mouse_up_events: Rc<RefCell<Vec<event::MouseUpEvent>>>,
pub touch_start_events: Rc<RefCell<Vec<event::TouchStart>>>,
pub touch_end_events: Rc<RefCell<Vec<event::TouchEnd>>>,
pub touch_move_events: Rc<RefCell<Vec<event::TouchMove>>>,
pub mouse_down_events: Rc<RefCell<Vec<event::MouseDownEvent>>>,
pub scroll_events: Rc<RefCell<Vec<event::MouseWheelEvent>>>,
pub key_up_events: Rc<RefCell<Vec<event::KeyUpEvent>>>,
pub key_down_events: Rc<RefCell<Vec<event::KeyDownEvent>>>,
pub resize_events: Rc<RefCell<Vec<event::ResizeEvent>>>,
}
| EventState | identifier_name |
states.rs | use std::{cell::RefCell, rc::Rc};
use stdweb::web::event;
/// Used to store and read web events.
pub struct EventState { | pub touch_start_events: Rc<RefCell<Vec<event::TouchStart>>>,
pub touch_end_events: Rc<RefCell<Vec<event::TouchEnd>>>,
pub touch_move_events: Rc<RefCell<Vec<event::TouchMove>>>,
pub mouse_down_events: Rc<RefCell<Vec<event::MouseDownEvent>>>,
pub scroll_events: Rc<RefCell<Vec<event::MouseWheelEvent>>>,
pub key_up_events: Rc<RefCell<Vec<event::KeyUpEvent>>>,
pub key_down_events: Rc<RefCell<Vec<event::KeyDownEvent>>>,
pub resize_events: Rc<RefCell<Vec<event::ResizeEvent>>>,
} | pub mouse_move_events: Rc<RefCell<Vec<event::MouseMoveEvent>>>,
pub mouse_up_events: Rc<RefCell<Vec<event::MouseUpEvent>>>, | random_line_split |
error.rs | use snafu::Snafu;
/// Represents an error during serialization/deserialization process
#[derive(Debug, Snafu)]
pub enum | {
#[snafu(display("Wrong encoding"))]
WrongEncoding {},
#[snafu(display("{}", source))]
#[snafu(context(false))]
UnknownSpecVersion {
source: crate::event::UnknownSpecVersion,
},
#[snafu(display("Unknown attribute in this spec version: {}", name))]
UnknownAttribute { name: String },
#[snafu(display("Error while building the final event: {}", source))]
#[snafu(context(false))]
EventBuilderError {
source: crate::event::EventBuilderError,
},
#[snafu(display("Error while parsing a time string: {}", source))]
#[snafu(context(false))]
ParseTimeError { source: chrono::ParseError },
#[snafu(display("Error while parsing a url: {}", source))]
#[snafu(context(false))]
ParseUrlError { source: url::ParseError },
#[snafu(display("Error while decoding base64: {}", source))]
#[snafu(context(false))]
Base64DecodingError { source: base64::DecodeError },
#[snafu(display("Error while serializing/deserializing to json: {}", source))]
#[snafu(context(false))]
SerdeJsonError { source: serde_json::Error },
#[snafu(display("IO Error: {}", source))]
#[snafu(context(false))]
IOError { source: std::io::Error },
#[snafu(display("Other error: {}", source))]
Other {
source: Box<dyn std::error::Error + Send + Sync>,
},
}
/// Result type alias for return values during serialization/deserialization process
pub type Result<T> = std::result::Result<T, Error>;
| Error | identifier_name |
error.rs | use snafu::Snafu;
/// Represents an error during serialization/deserialization process
#[derive(Debug, Snafu)]
pub enum Error {
#[snafu(display("Wrong encoding"))]
WrongEncoding {},
#[snafu(display("{}", source))]
#[snafu(context(false))]
UnknownSpecVersion {
source: crate::event::UnknownSpecVersion,
},
#[snafu(display("Unknown attribute in this spec version: {}", name))]
UnknownAttribute { name: String },
#[snafu(display("Error while building the final event: {}", source))]
#[snafu(context(false))]
EventBuilderError {
source: crate::event::EventBuilderError,
},
#[snafu(display("Error while parsing a time string: {}", source))]
#[snafu(context(false))]
ParseTimeError { source: chrono::ParseError },
#[snafu(display("Error while parsing a url: {}", source))]
#[snafu(context(false))]
ParseUrlError { source: url::ParseError },
#[snafu(display("Error while decoding base64: {}", source))]
#[snafu(context(false))]
Base64DecodingError { source: base64::DecodeError },
#[snafu(display("Error while serializing/deserializing to json: {}", source))]
#[snafu(context(false))]
SerdeJsonError { source: serde_json::Error }, | IOError { source: std::io::Error },
#[snafu(display("Other error: {}", source))]
Other {
source: Box<dyn std::error::Error + Send + Sync>,
},
}
/// Result type alias for return values during serialization/deserialization process
pub type Result<T> = std::result::Result<T, Error>; | #[snafu(display("IO Error: {}", source))]
#[snafu(context(false))] | random_line_split |
mod.rs | use byteorder::{BigEndian, WriteBytesExt};
use db;
use std::cmp;
use std::io::Cursor;
pub mod bloomfilter;
#[macro_export]
macro_rules! retry_bound {
($k:expr) => {
if $k < 9 { // special case since formula yields a very loose upper bound for k < 9
$k as u32 // we can always retrieve k elements in k rounds
} else {
3 * (($k as f64).ln() / ($k as f64).ln().ln()).ceil() as u32
}
};
($k:expr, $d:expr) => {
if $k < 3 { // special case since formula yields a very loose upper bound for k < 3
$k as u32
} else {
((($k as f64).ln().ln() / ($d as f64).ln()) + 1.0).ceil() as u32
}
};
}
#[macro_export]
macro_rules! some_or_random {
($res:expr, $rng:expr, $len:expr) => {
if let Some(idx) = $res {
idx
} else {
$rng.next_u64() % ($len as u64)
}
};
}
// Below is unsafe
#[inline]
pub fn label_cmp(l1: &[u8], l2: &[u8]) -> cmp::Ordering |
#[inline]
pub fn tree_height(num: u64) -> u32 {
((num + 1) as f64).log2().ceil() as u32
}
#[inline]
pub fn get_index(labels: &[Vec<u8>], label: &[u8]) -> Option<u64> {
match labels.binary_search_by(|probe| label_cmp(&probe[..], label)) {
Ok(i) => Some(i as u64),
Err(_) => None,
}
}
#[inline]
pub fn get_idx_bloom(bloom: &bloomfilter::Bloom, label: &[u8], num: u64) -> Option<u64> {
for i in 0..(num as usize) {
if bloom.check((i, label)) {
return Some(i as u64);
}
}
None
}
// Returns number of elements in collection for given collection_idx (this assumes hybrid 2 or 4)
pub fn collection_len(bucket_len: u64, collection_idx: u32, num_collections: u32) -> u64 {
if num_collections == 1 {
bucket_len
} else if num_collections == 2 {
// hybrid 2
match collection_idx {
0 => (bucket_len as f64 / 2f64).ceil() as u64,
1 => bucket_len / 2,
_ => panic!("Invalid collection idx"),
}
} else if num_collections == 4 {
// hybrid 4
match collection_idx {
0 => ((bucket_len as f64 / 2f64).ceil() / 2f64).ceil() as u64,
1 => ((bucket_len as f64 / 2f64).ceil() / 2f64).floor() as u64,
2 => ((bucket_len as f64 / 2f64).floor() / 2f64).ceil() as u64,
3 => bucket_len / 4,
_ => panic!("Invalid collection idx"),
}
} else {
panic!("Invalid num collections");
}
}
// Returns the indices of collections that contain a meaningful label
#[inline]
pub fn label_collections(scheme: db::OptScheme) -> Vec<usize> {
match scheme {
db::OptScheme::Normal | db::OptScheme::Aliasing => vec![0],
db::OptScheme::Hybrid2 => vec![0, 1], // labels are in collections 0 and 1
db::OptScheme::Hybrid4 => vec![0, 1, 2, 3], // labels are in collections 0, 1, 2, and 3
}
}
#[inline]
pub fn label_marker(index: usize, buckets: usize) -> Vec<u8> {
assert!(index < buckets);
let max = u32::max_value();
let mut limit = max / buckets as u32;
limit *= (index as u32) + 1;
let mut a = Cursor::new(Vec::with_capacity(4));
a.write_u32::<BigEndian>(limit).unwrap();
a.into_inner()
}
#[inline]
pub fn bucket_idx(label: &[u8], partitions: &[Vec<u8>]) -> usize {
for (i, partition) in partitions.iter().enumerate() {
if label <= &partition[..] {
return i;
}
}
0
}
#[inline]
pub fn get_alpha(num: u64) -> u64 {
if db::CIPHER_SIZE <= 240 {
if num < 8 {
1
} else if num < 2048 {
8
} else if num < 65536 {
32
} else {
64
}
} else if db::CIPHER_SIZE <= 1024 {
if num < 8 {
1
} else if num < 32768 {
8
} else if num < 131072 {
16
} else {
32
}
} else if num < 32768 {
1
} else {
8
}
}
| {
unsafe {
(&*(l1 as *const [u8] as *const [u64; 4])).cmp(&*(l2 as *const [u8] as *const [u64; 4]))
}
} | identifier_body |
mod.rs | use byteorder::{BigEndian, WriteBytesExt};
use db;
use std::cmp;
use std::io::Cursor;
pub mod bloomfilter;
#[macro_export]
macro_rules! retry_bound {
($k:expr) => {
if $k < 9 { // special case since formula yields a very loose upper bound for k < 9
$k as u32 // we can always retrieve k elements in k rounds
} else {
3 * (($k as f64).ln() / ($k as f64).ln().ln()).ceil() as u32
}
};
($k:expr, $d:expr) => {
if $k < 3 { // special case since formula yields a very loose upper bound for k < 3
$k as u32
} else {
((($k as f64).ln().ln() / ($d as f64).ln()) + 1.0).ceil() as u32
}
};
}
#[macro_export]
macro_rules! some_or_random {
($res:expr, $rng:expr, $len:expr) => {
if let Some(idx) = $res {
idx
} else {
$rng.next_u64() % ($len as u64)
}
};
}
// Below is unsafe
#[inline]
pub fn label_cmp(l1: &[u8], l2: &[u8]) -> cmp::Ordering {
unsafe {
(&*(l1 as *const [u8] as *const [u64; 4])).cmp(&*(l2 as *const [u8] as *const [u64; 4]))
}
}
#[inline]
pub fn tree_height(num: u64) -> u32 {
((num + 1) as f64).log2().ceil() as u32
}
#[inline]
pub fn get_index(labels: &[Vec<u8>], label: &[u8]) -> Option<u64> {
match labels.binary_search_by(|probe| label_cmp(&probe[..], label)) {
Ok(i) => Some(i as u64),
Err(_) => None,
}
}
#[inline]
pub fn get_idx_bloom(bloom: &bloomfilter::Bloom, label: &[u8], num: u64) -> Option<u64> {
for i in 0..(num as usize) {
if bloom.check((i, label)) {
return Some(i as u64);
}
}
None
}
// Returns number of elements in collection for given collection_idx (this assumes hybrid 2 or 4)
pub fn collection_len(bucket_len: u64, collection_idx: u32, num_collections: u32) -> u64 {
if num_collections == 1 {
bucket_len
} else if num_collections == 2 {
// hybrid 2
match collection_idx {
0 => (bucket_len as f64 / 2f64).ceil() as u64,
1 => bucket_len / 2,
_ => panic!("Invalid collection idx"),
}
} else if num_collections == 4 {
// hybrid 4
match collection_idx {
0 => ((bucket_len as f64 / 2f64).ceil() / 2f64).ceil() as u64,
1 => ((bucket_len as f64 / 2f64).ceil() / 2f64).floor() as u64,
2 => ((bucket_len as f64 / 2f64).floor() / 2f64).ceil() as u64,
3 => bucket_len / 4,
_ => panic!("Invalid collection idx"),
}
} else {
panic!("Invalid num collections");
}
}
// Returns the indices of collections that contain a meaningful label
#[inline]
pub fn label_collections(scheme: db::OptScheme) -> Vec<usize> {
match scheme {
db::OptScheme::Normal | db::OptScheme::Aliasing => vec![0],
db::OptScheme::Hybrid2 => vec![0, 1], // labels are in collections 0 and 1
db::OptScheme::Hybrid4 => vec![0, 1, 2, 3], // labels are in collections 0, 1, 2, and 3
}
}
#[inline]
pub fn label_marker(index: usize, buckets: usize) -> Vec<u8> {
assert!(index < buckets);
let max = u32::max_value();
let mut limit = max / buckets as u32;
limit *= (index as u32) + 1;
let mut a = Cursor::new(Vec::with_capacity(4));
a.write_u32::<BigEndian>(limit).unwrap();
a.into_inner()
}
#[inline]
pub fn bucket_idx(label: &[u8], partitions: &[Vec<u8>]) -> usize {
for (i, partition) in partitions.iter().enumerate() {
if label <= &partition[..] {
return i;
}
}
0
}
#[inline]
pub fn get_alpha(num: u64) -> u64 {
if db::CIPHER_SIZE <= 240 {
if num < 8 {
1
} else if num < 2048 {
8
} else if num < 65536 {
32
} else {
64 | } else if db::CIPHER_SIZE <= 1024 {
if num < 8 {
1
} else if num < 32768 {
8
} else if num < 131072 {
16
} else {
32
}
} else if num < 32768 {
1
} else {
8
}
} | } | random_line_split |
mod.rs | use byteorder::{BigEndian, WriteBytesExt};
use db;
use std::cmp;
use std::io::Cursor;
pub mod bloomfilter;
#[macro_export]
macro_rules! retry_bound {
($k:expr) => {
if $k < 9 { // special case since formula yields a very loose upper bound for k < 9
$k as u32 // we can always retrieve k elements in k rounds
} else {
3 * (($k as f64).ln() / ($k as f64).ln().ln()).ceil() as u32
}
};
($k:expr, $d:expr) => {
if $k < 3 { // special case since formula yields a very loose upper bound for k < 3
$k as u32
} else {
((($k as f64).ln().ln() / ($d as f64).ln()) + 1.0).ceil() as u32
}
};
}
#[macro_export]
macro_rules! some_or_random {
($res:expr, $rng:expr, $len:expr) => {
if let Some(idx) = $res {
idx
} else {
$rng.next_u64() % ($len as u64)
}
};
}
// Below is unsafe
#[inline]
pub fn label_cmp(l1: &[u8], l2: &[u8]) -> cmp::Ordering {
unsafe {
(&*(l1 as *const [u8] as *const [u64; 4])).cmp(&*(l2 as *const [u8] as *const [u64; 4]))
}
}
#[inline]
pub fn tree_height(num: u64) -> u32 {
((num + 1) as f64).log2().ceil() as u32
}
#[inline]
pub fn get_index(labels: &[Vec<u8>], label: &[u8]) -> Option<u64> {
match labels.binary_search_by(|probe| label_cmp(&probe[..], label)) {
Ok(i) => Some(i as u64),
Err(_) => None,
}
}
#[inline]
pub fn get_idx_bloom(bloom: &bloomfilter::Bloom, label: &[u8], num: u64) -> Option<u64> {
for i in 0..(num as usize) {
if bloom.check((i, label)) {
return Some(i as u64);
}
}
None
}
// Returns number of elements in collection for given collection_idx (this assumes hybrid 2 or 4)
pub fn collection_len(bucket_len: u64, collection_idx: u32, num_collections: u32) -> u64 {
if num_collections == 1 {
bucket_len
} else if num_collections == 2 {
// hybrid 2
match collection_idx {
0 => (bucket_len as f64 / 2f64).ceil() as u64,
1 => bucket_len / 2,
_ => panic!("Invalid collection idx"),
}
} else if num_collections == 4 {
// hybrid 4
match collection_idx {
0 => ((bucket_len as f64 / 2f64).ceil() / 2f64).ceil() as u64,
1 => ((bucket_len as f64 / 2f64).ceil() / 2f64).floor() as u64,
2 => ((bucket_len as f64 / 2f64).floor() / 2f64).ceil() as u64,
3 => bucket_len / 4,
_ => panic!("Invalid collection idx"),
}
} else {
panic!("Invalid num collections");
}
}
// Returns the indices of collections that contain a meaningful label
#[inline]
pub fn label_collections(scheme: db::OptScheme) -> Vec<usize> {
match scheme {
db::OptScheme::Normal | db::OptScheme::Aliasing => vec![0],
db::OptScheme::Hybrid2 => vec![0, 1], // labels are in collections 0 and 1
db::OptScheme::Hybrid4 => vec![0, 1, 2, 3], // labels are in collections 0, 1, 2, and 3
}
}
#[inline]
pub fn label_marker(index: usize, buckets: usize) -> Vec<u8> {
assert!(index < buckets);
let max = u32::max_value();
let mut limit = max / buckets as u32;
limit *= (index as u32) + 1;
let mut a = Cursor::new(Vec::with_capacity(4));
a.write_u32::<BigEndian>(limit).unwrap();
a.into_inner()
}
#[inline]
pub fn bucket_idx(label: &[u8], partitions: &[Vec<u8>]) -> usize {
for (i, partition) in partitions.iter().enumerate() {
if label <= &partition[..] {
return i;
}
}
0
}
#[inline]
pub fn get_alpha(num: u64) -> u64 {
if db::CIPHER_SIZE <= 240 {
if num < 8 {
1
} else if num < 2048 {
8
} else if num < 65536 {
32
} else |
} else if db::CIPHER_SIZE <= 1024 {
if num < 8 {
1
} else if num < 32768 {
8
} else if num < 131072 {
16
} else {
32
}
} else if num < 32768 {
1
} else {
8
}
}
| {
64
} | conditional_block |
mod.rs | use byteorder::{BigEndian, WriteBytesExt};
use db;
use std::cmp;
use std::io::Cursor;
pub mod bloomfilter;
#[macro_export]
macro_rules! retry_bound {
($k:expr) => {
if $k < 9 { // special case since formula yields a very loose upper bound for k < 9
$k as u32 // we can always retrieve k elements in k rounds
} else {
3 * (($k as f64).ln() / ($k as f64).ln().ln()).ceil() as u32
}
};
($k:expr, $d:expr) => {
if $k < 3 { // special case since formula yields a very loose upper bound for k < 3
$k as u32
} else {
((($k as f64).ln().ln() / ($d as f64).ln()) + 1.0).ceil() as u32
}
};
}
#[macro_export]
macro_rules! some_or_random {
($res:expr, $rng:expr, $len:expr) => {
if let Some(idx) = $res {
idx
} else {
$rng.next_u64() % ($len as u64)
}
};
}
// Below is unsafe
#[inline]
pub fn label_cmp(l1: &[u8], l2: &[u8]) -> cmp::Ordering {
unsafe {
(&*(l1 as *const [u8] as *const [u64; 4])).cmp(&*(l2 as *const [u8] as *const [u64; 4]))
}
}
#[inline]
pub fn tree_height(num: u64) -> u32 {
((num + 1) as f64).log2().ceil() as u32
}
#[inline]
pub fn get_index(labels: &[Vec<u8>], label: &[u8]) -> Option<u64> {
match labels.binary_search_by(|probe| label_cmp(&probe[..], label)) {
Ok(i) => Some(i as u64),
Err(_) => None,
}
}
#[inline]
pub fn get_idx_bloom(bloom: &bloomfilter::Bloom, label: &[u8], num: u64) -> Option<u64> {
for i in 0..(num as usize) {
if bloom.check((i, label)) {
return Some(i as u64);
}
}
None
}
// Returns number of elements in collection for given collection_idx (this assumes hybrid 2 or 4)
pub fn | (bucket_len: u64, collection_idx: u32, num_collections: u32) -> u64 {
if num_collections == 1 {
bucket_len
} else if num_collections == 2 {
// hybrid 2
match collection_idx {
0 => (bucket_len as f64 / 2f64).ceil() as u64,
1 => bucket_len / 2,
_ => panic!("Invalid collection idx"),
}
} else if num_collections == 4 {
// hybrid 4
match collection_idx {
0 => ((bucket_len as f64 / 2f64).ceil() / 2f64).ceil() as u64,
1 => ((bucket_len as f64 / 2f64).ceil() / 2f64).floor() as u64,
2 => ((bucket_len as f64 / 2f64).floor() / 2f64).ceil() as u64,
3 => bucket_len / 4,
_ => panic!("Invalid collection idx"),
}
} else {
panic!("Invalid num collections");
}
}
// Returns the indices of collections that contain a meaningful label
#[inline]
pub fn label_collections(scheme: db::OptScheme) -> Vec<usize> {
match scheme {
db::OptScheme::Normal | db::OptScheme::Aliasing => vec![0],
db::OptScheme::Hybrid2 => vec![0, 1], // labels are in collections 0 and 1
db::OptScheme::Hybrid4 => vec![0, 1, 2, 3], // labels are in collections 0, 1, 2, and 3
}
}
#[inline]
pub fn label_marker(index: usize, buckets: usize) -> Vec<u8> {
assert!(index < buckets);
let max = u32::max_value();
let mut limit = max / buckets as u32;
limit *= (index as u32) + 1;
let mut a = Cursor::new(Vec::with_capacity(4));
a.write_u32::<BigEndian>(limit).unwrap();
a.into_inner()
}
#[inline]
pub fn bucket_idx(label: &[u8], partitions: &[Vec<u8>]) -> usize {
for (i, partition) in partitions.iter().enumerate() {
if label <= &partition[..] {
return i;
}
}
0
}
#[inline]
pub fn get_alpha(num: u64) -> u64 {
if db::CIPHER_SIZE <= 240 {
if num < 8 {
1
} else if num < 2048 {
8
} else if num < 65536 {
32
} else {
64
}
} else if db::CIPHER_SIZE <= 1024 {
if num < 8 {
1
} else if num < 32768 {
8
} else if num < 131072 {
16
} else {
32
}
} else if num < 32768 {
1
} else {
8
}
}
| collection_len | identifier_name |
mod.rs | //! # Schemes
//! A scheme is a primitive for handling filesystem syscalls in Redox.
//! Schemes accept paths from the kernel for `open`, and file descriptors that they generate
//! are then passed for operations like `close`, `read`, `write`, etc.
//!
//! The kernel validates paths and file descriptors before they are passed to schemes,
//! also stripping the scheme identifier of paths if necessary.
use alloc::arc::Arc;
use alloc::boxed::Box;
use collections::BTreeMap;
use core::sync::atomic::Ordering;
use spin::{Once, RwLock, RwLockReadGuard, RwLockWriteGuard};
use syscall::error::*;
use syscall::scheme::Scheme;
use self::debug::{DEBUG_SCHEME_ID, DebugScheme};
use self::event::EventScheme;
use self::env::EnvScheme;
use self::initfs::InitFsScheme;
use self::irq::{IRQ_SCHEME_ID, IrqScheme};
use self::null::NullScheme;
use self::pipe::{PIPE_SCHEME_ID, PipeScheme};
use self::root::{ROOT_SCHEME_ID, RootScheme};
use self::sys::SysScheme;
use self::zero::ZeroScheme;
/// Debug scheme
pub mod debug;
/// Kernel events
pub mod event;
/// Environmental variables
pub mod env;
/// InitFS scheme
pub mod initfs;
/// IRQ handling
pub mod irq;
/// Null scheme
pub mod null;
/// Anonymouse pipe
pub mod pipe;
/// Root scheme
pub mod root;
/// System information
pub mod sys;
/// Userspace schemes
pub mod user;
/// Zero scheme
pub mod zero;
/// Limit on number of schemes
pub const SCHEME_MAX_SCHEMES: usize = 65536;
/// Scheme list type
pub struct SchemeList {
map: BTreeMap<usize, Arc<Box<Scheme + Send + Sync>>>,
names: BTreeMap<Box<[u8]>, usize>,
next_id: usize
}
impl SchemeList {
/// Create a new scheme list.
pub fn new() -> Self |
pub fn iter(&self) -> ::collections::btree_map::Iter<usize, Arc<Box<Scheme + Send + Sync>>> {
self.map.iter()
}
pub fn iter_name(&self) -> ::collections::btree_map::Iter<Box<[u8]>, usize> {
self.names.iter()
}
/// Get the nth scheme.
pub fn get(&self, id: usize) -> Option<&Arc<Box<Scheme + Send + Sync>>> {
self.map.get(&id)
}
pub fn get_name(&self, name: &[u8]) -> Option<(usize, &Arc<Box<Scheme + Send + Sync>>)> {
if let Some(&id) = self.names.get(name) {
self.get(id).map(|scheme| (id, scheme))
} else {
None
}
}
/// Create a new scheme.
pub fn insert(&mut self, name: Box<[u8]>, scheme: Arc<Box<Scheme + Send + Sync>>) -> Result<usize> {
if self.names.contains_key(&name) {
return Err(Error::new(EEXIST));
}
if self.next_id >= SCHEME_MAX_SCHEMES {
self.next_id = 1;
}
while self.map.contains_key(&self.next_id) {
self.next_id += 1;
}
if self.next_id >= SCHEME_MAX_SCHEMES {
return Err(Error::new(EAGAIN));
}
let id = self.next_id;
self.next_id += 1;
assert!(self.map.insert(id, scheme).is_none());
assert!(self.names.insert(name, id).is_none());
Ok(id)
}
}
/// Schemes list
static SCHEMES: Once<RwLock<SchemeList>> = Once::new();
/// Initialize schemes, called if needed
fn init_schemes() -> RwLock<SchemeList> {
let mut list: SchemeList = SchemeList::new();
ROOT_SCHEME_ID.store(list.insert(Box::new(*b""), Arc::new(Box::new(RootScheme::new()))).expect("failed to insert root scheme"), Ordering::SeqCst);
DEBUG_SCHEME_ID.store(list.insert(Box::new(*b"debug"), Arc::new(Box::new(DebugScheme))).expect("failed to insert debug scheme"), Ordering::SeqCst);
list.insert(Box::new(*b"event"), Arc::new(Box::new(EventScheme::new()))).expect("failed to insert event scheme");
list.insert(Box::new(*b"env"), Arc::new(Box::new(EnvScheme::new()))).expect("failed to insert env scheme");
list.insert(Box::new(*b"initfs"), Arc::new(Box::new(InitFsScheme::new()))).expect("failed to insert initfs scheme");
IRQ_SCHEME_ID.store(list.insert(Box::new(*b"irq"), Arc::new(Box::new(IrqScheme))).expect("failed to insert irq scheme"), Ordering::SeqCst);
list.insert(Box::new(*b"null"), Arc::new(Box::new(NullScheme))).expect("failed to insert null scheme");
PIPE_SCHEME_ID.store(list.insert(Box::new(*b"pipe"), Arc::new(Box::new(PipeScheme))).expect("failed to insert pipe scheme"), Ordering::SeqCst);
list.insert(Box::new(*b"sys"), Arc::new(Box::new(SysScheme::new()))).expect("failed to insert sys scheme");
list.insert(Box::new(*b"zero"), Arc::new(Box::new(ZeroScheme))).expect("failed to insert zero scheme");
RwLock::new(list)
}
/// Get the global schemes list, const
pub fn schemes() -> RwLockReadGuard<'static, SchemeList> {
SCHEMES.call_once(init_schemes).read()
}
/// Get the global schemes list, mutable
pub fn schemes_mut() -> RwLockWriteGuard<'static, SchemeList> {
SCHEMES.call_once(init_schemes).write()
}
| {
SchemeList {
map: BTreeMap::new(),
names: BTreeMap::new(),
next_id: 1
}
} | identifier_body |
mod.rs | //! # Schemes
//! A scheme is a primitive for handling filesystem syscalls in Redox.
//! Schemes accept paths from the kernel for `open`, and file descriptors that they generate
//! are then passed for operations like `close`, `read`, `write`, etc.
//!
//! The kernel validates paths and file descriptors before they are passed to schemes,
//! also stripping the scheme identifier of paths if necessary.
use alloc::arc::Arc;
use alloc::boxed::Box;
use collections::BTreeMap;
use core::sync::atomic::Ordering;
use spin::{Once, RwLock, RwLockReadGuard, RwLockWriteGuard};
use syscall::error::*;
use syscall::scheme::Scheme;
use self::debug::{DEBUG_SCHEME_ID, DebugScheme};
use self::event::EventScheme;
use self::env::EnvScheme;
use self::initfs::InitFsScheme;
use self::irq::{IRQ_SCHEME_ID, IrqScheme};
use self::null::NullScheme;
use self::pipe::{PIPE_SCHEME_ID, PipeScheme};
use self::root::{ROOT_SCHEME_ID, RootScheme};
use self::sys::SysScheme;
use self::zero::ZeroScheme;
/// Debug scheme
pub mod debug;
/// Kernel events
pub mod event;
/// Environmental variables
pub mod env;
/// InitFS scheme
pub mod initfs;
/// IRQ handling
pub mod irq;
/// Null scheme
pub mod null;
/// Anonymouse pipe
pub mod pipe;
/// Root scheme
pub mod root;
/// System information
pub mod sys;
/// Userspace schemes
pub mod user;
/// Zero scheme
pub mod zero;
/// Limit on number of schemes
pub const SCHEME_MAX_SCHEMES: usize = 65536;
/// Scheme list type
pub struct SchemeList {
map: BTreeMap<usize, Arc<Box<Scheme + Send + Sync>>>,
names: BTreeMap<Box<[u8]>, usize>,
next_id: usize
}
impl SchemeList {
/// Create a new scheme list.
pub fn new() -> Self {
SchemeList {
map: BTreeMap::new(),
names: BTreeMap::new(),
next_id: 1
}
}
pub fn iter(&self) -> ::collections::btree_map::Iter<usize, Arc<Box<Scheme + Send + Sync>>> {
self.map.iter()
}
pub fn iter_name(&self) -> ::collections::btree_map::Iter<Box<[u8]>, usize> {
self.names.iter()
}
/// Get the nth scheme.
pub fn get(&self, id: usize) -> Option<&Arc<Box<Scheme + Send + Sync>>> {
self.map.get(&id)
}
pub fn get_name(&self, name: &[u8]) -> Option<(usize, &Arc<Box<Scheme + Send + Sync>>)> {
if let Some(&id) = self.names.get(name) {
self.get(id).map(|scheme| (id, scheme))
} else {
None
}
}
/// Create a new scheme.
pub fn insert(&mut self, name: Box<[u8]>, scheme: Arc<Box<Scheme + Send + Sync>>) -> Result<usize> {
if self.names.contains_key(&name) {
return Err(Error::new(EEXIST));
}
if self.next_id >= SCHEME_MAX_SCHEMES {
self.next_id = 1;
}
while self.map.contains_key(&self.next_id) {
self.next_id += 1;
}
if self.next_id >= SCHEME_MAX_SCHEMES {
return Err(Error::new(EAGAIN));
}
let id = self.next_id;
self.next_id += 1;
assert!(self.map.insert(id, scheme).is_none());
assert!(self.names.insert(name, id).is_none());
Ok(id)
}
}
/// Schemes list
static SCHEMES: Once<RwLock<SchemeList>> = Once::new();
/// Initialize schemes, called if needed
fn init_schemes() -> RwLock<SchemeList> {
let mut list: SchemeList = SchemeList::new();
ROOT_SCHEME_ID.store(list.insert(Box::new(*b""), Arc::new(Box::new(RootScheme::new()))).expect("failed to insert root scheme"), Ordering::SeqCst);
DEBUG_SCHEME_ID.store(list.insert(Box::new(*b"debug"), Arc::new(Box::new(DebugScheme))).expect("failed to insert debug scheme"), Ordering::SeqCst);
list.insert(Box::new(*b"event"), Arc::new(Box::new(EventScheme::new()))).expect("failed to insert event scheme");
list.insert(Box::new(*b"env"), Arc::new(Box::new(EnvScheme::new()))).expect("failed to insert env scheme");
list.insert(Box::new(*b"initfs"), Arc::new(Box::new(InitFsScheme::new()))).expect("failed to insert initfs scheme");
IRQ_SCHEME_ID.store(list.insert(Box::new(*b"irq"), Arc::new(Box::new(IrqScheme))).expect("failed to insert irq scheme"), Ordering::SeqCst);
list.insert(Box::new(*b"null"), Arc::new(Box::new(NullScheme))).expect("failed to insert null scheme");
PIPE_SCHEME_ID.store(list.insert(Box::new(*b"pipe"), Arc::new(Box::new(PipeScheme))).expect("failed to insert pipe scheme"), Ordering::SeqCst); | RwLock::new(list)
}
/// Get the global schemes list, const
pub fn schemes() -> RwLockReadGuard<'static, SchemeList> {
SCHEMES.call_once(init_schemes).read()
}
/// Get the global schemes list, mutable
pub fn schemes_mut() -> RwLockWriteGuard<'static, SchemeList> {
SCHEMES.call_once(init_schemes).write()
} | list.insert(Box::new(*b"sys"), Arc::new(Box::new(SysScheme::new()))).expect("failed to insert sys scheme");
list.insert(Box::new(*b"zero"), Arc::new(Box::new(ZeroScheme))).expect("failed to insert zero scheme"); | random_line_split |
mod.rs | //! # Schemes
//! A scheme is a primitive for handling filesystem syscalls in Redox.
//! Schemes accept paths from the kernel for `open`, and file descriptors that they generate
//! are then passed for operations like `close`, `read`, `write`, etc.
//!
//! The kernel validates paths and file descriptors before they are passed to schemes,
//! also stripping the scheme identifier of paths if necessary.
use alloc::arc::Arc;
use alloc::boxed::Box;
use collections::BTreeMap;
use core::sync::atomic::Ordering;
use spin::{Once, RwLock, RwLockReadGuard, RwLockWriteGuard};
use syscall::error::*;
use syscall::scheme::Scheme;
use self::debug::{DEBUG_SCHEME_ID, DebugScheme};
use self::event::EventScheme;
use self::env::EnvScheme;
use self::initfs::InitFsScheme;
use self::irq::{IRQ_SCHEME_ID, IrqScheme};
use self::null::NullScheme;
use self::pipe::{PIPE_SCHEME_ID, PipeScheme};
use self::root::{ROOT_SCHEME_ID, RootScheme};
use self::sys::SysScheme;
use self::zero::ZeroScheme;
/// Debug scheme
pub mod debug;
/// Kernel events
pub mod event;
/// Environmental variables
pub mod env;
/// InitFS scheme
pub mod initfs;
/// IRQ handling
pub mod irq;
/// Null scheme
pub mod null;
/// Anonymouse pipe
pub mod pipe;
/// Root scheme
pub mod root;
/// System information
pub mod sys;
/// Userspace schemes
pub mod user;
/// Zero scheme
pub mod zero;
/// Limit on number of schemes
pub const SCHEME_MAX_SCHEMES: usize = 65536;
/// Scheme list type
pub struct SchemeList {
map: BTreeMap<usize, Arc<Box<Scheme + Send + Sync>>>,
names: BTreeMap<Box<[u8]>, usize>,
next_id: usize
}
impl SchemeList {
/// Create a new scheme list.
pub fn new() -> Self {
SchemeList {
map: BTreeMap::new(),
names: BTreeMap::new(),
next_id: 1
}
}
pub fn iter(&self) -> ::collections::btree_map::Iter<usize, Arc<Box<Scheme + Send + Sync>>> {
self.map.iter()
}
pub fn iter_name(&self) -> ::collections::btree_map::Iter<Box<[u8]>, usize> {
self.names.iter()
}
/// Get the nth scheme.
pub fn get(&self, id: usize) -> Option<&Arc<Box<Scheme + Send + Sync>>> {
self.map.get(&id)
}
pub fn | (&self, name: &[u8]) -> Option<(usize, &Arc<Box<Scheme + Send + Sync>>)> {
if let Some(&id) = self.names.get(name) {
self.get(id).map(|scheme| (id, scheme))
} else {
None
}
}
/// Create a new scheme.
pub fn insert(&mut self, name: Box<[u8]>, scheme: Arc<Box<Scheme + Send + Sync>>) -> Result<usize> {
if self.names.contains_key(&name) {
return Err(Error::new(EEXIST));
}
if self.next_id >= SCHEME_MAX_SCHEMES {
self.next_id = 1;
}
while self.map.contains_key(&self.next_id) {
self.next_id += 1;
}
if self.next_id >= SCHEME_MAX_SCHEMES {
return Err(Error::new(EAGAIN));
}
let id = self.next_id;
self.next_id += 1;
assert!(self.map.insert(id, scheme).is_none());
assert!(self.names.insert(name, id).is_none());
Ok(id)
}
}
/// Schemes list
static SCHEMES: Once<RwLock<SchemeList>> = Once::new();
/// Initialize schemes, called if needed
fn init_schemes() -> RwLock<SchemeList> {
let mut list: SchemeList = SchemeList::new();
ROOT_SCHEME_ID.store(list.insert(Box::new(*b""), Arc::new(Box::new(RootScheme::new()))).expect("failed to insert root scheme"), Ordering::SeqCst);
DEBUG_SCHEME_ID.store(list.insert(Box::new(*b"debug"), Arc::new(Box::new(DebugScheme))).expect("failed to insert debug scheme"), Ordering::SeqCst);
list.insert(Box::new(*b"event"), Arc::new(Box::new(EventScheme::new()))).expect("failed to insert event scheme");
list.insert(Box::new(*b"env"), Arc::new(Box::new(EnvScheme::new()))).expect("failed to insert env scheme");
list.insert(Box::new(*b"initfs"), Arc::new(Box::new(InitFsScheme::new()))).expect("failed to insert initfs scheme");
IRQ_SCHEME_ID.store(list.insert(Box::new(*b"irq"), Arc::new(Box::new(IrqScheme))).expect("failed to insert irq scheme"), Ordering::SeqCst);
list.insert(Box::new(*b"null"), Arc::new(Box::new(NullScheme))).expect("failed to insert null scheme");
PIPE_SCHEME_ID.store(list.insert(Box::new(*b"pipe"), Arc::new(Box::new(PipeScheme))).expect("failed to insert pipe scheme"), Ordering::SeqCst);
list.insert(Box::new(*b"sys"), Arc::new(Box::new(SysScheme::new()))).expect("failed to insert sys scheme");
list.insert(Box::new(*b"zero"), Arc::new(Box::new(ZeroScheme))).expect("failed to insert zero scheme");
RwLock::new(list)
}
/// Get the global schemes list, const
pub fn schemes() -> RwLockReadGuard<'static, SchemeList> {
SCHEMES.call_once(init_schemes).read()
}
/// Get the global schemes list, mutable
pub fn schemes_mut() -> RwLockWriteGuard<'static, SchemeList> {
SCHEMES.call_once(init_schemes).write()
}
| get_name | identifier_name |
mod.rs | //! # Schemes
//! A scheme is a primitive for handling filesystem syscalls in Redox.
//! Schemes accept paths from the kernel for `open`, and file descriptors that they generate
//! are then passed for operations like `close`, `read`, `write`, etc.
//!
//! The kernel validates paths and file descriptors before they are passed to schemes,
//! also stripping the scheme identifier of paths if necessary.
use alloc::arc::Arc;
use alloc::boxed::Box;
use collections::BTreeMap;
use core::sync::atomic::Ordering;
use spin::{Once, RwLock, RwLockReadGuard, RwLockWriteGuard};
use syscall::error::*;
use syscall::scheme::Scheme;
use self::debug::{DEBUG_SCHEME_ID, DebugScheme};
use self::event::EventScheme;
use self::env::EnvScheme;
use self::initfs::InitFsScheme;
use self::irq::{IRQ_SCHEME_ID, IrqScheme};
use self::null::NullScheme;
use self::pipe::{PIPE_SCHEME_ID, PipeScheme};
use self::root::{ROOT_SCHEME_ID, RootScheme};
use self::sys::SysScheme;
use self::zero::ZeroScheme;
/// Debug scheme
pub mod debug;
/// Kernel events
pub mod event;
/// Environmental variables
pub mod env;
/// InitFS scheme
pub mod initfs;
/// IRQ handling
pub mod irq;
/// Null scheme
pub mod null;
/// Anonymouse pipe
pub mod pipe;
/// Root scheme
pub mod root;
/// System information
pub mod sys;
/// Userspace schemes
pub mod user;
/// Zero scheme
pub mod zero;
/// Limit on number of schemes
pub const SCHEME_MAX_SCHEMES: usize = 65536;
/// Scheme list type
pub struct SchemeList {
map: BTreeMap<usize, Arc<Box<Scheme + Send + Sync>>>,
names: BTreeMap<Box<[u8]>, usize>,
next_id: usize
}
impl SchemeList {
/// Create a new scheme list.
pub fn new() -> Self {
SchemeList {
map: BTreeMap::new(),
names: BTreeMap::new(),
next_id: 1
}
}
pub fn iter(&self) -> ::collections::btree_map::Iter<usize, Arc<Box<Scheme + Send + Sync>>> {
self.map.iter()
}
pub fn iter_name(&self) -> ::collections::btree_map::Iter<Box<[u8]>, usize> {
self.names.iter()
}
/// Get the nth scheme.
pub fn get(&self, id: usize) -> Option<&Arc<Box<Scheme + Send + Sync>>> {
self.map.get(&id)
}
pub fn get_name(&self, name: &[u8]) -> Option<(usize, &Arc<Box<Scheme + Send + Sync>>)> {
if let Some(&id) = self.names.get(name) {
self.get(id).map(|scheme| (id, scheme))
} else {
None
}
}
/// Create a new scheme.
pub fn insert(&mut self, name: Box<[u8]>, scheme: Arc<Box<Scheme + Send + Sync>>) -> Result<usize> {
if self.names.contains_key(&name) |
if self.next_id >= SCHEME_MAX_SCHEMES {
self.next_id = 1;
}
while self.map.contains_key(&self.next_id) {
self.next_id += 1;
}
if self.next_id >= SCHEME_MAX_SCHEMES {
return Err(Error::new(EAGAIN));
}
let id = self.next_id;
self.next_id += 1;
assert!(self.map.insert(id, scheme).is_none());
assert!(self.names.insert(name, id).is_none());
Ok(id)
}
}
/// Schemes list
static SCHEMES: Once<RwLock<SchemeList>> = Once::new();
/// Initialize schemes, called if needed
fn init_schemes() -> RwLock<SchemeList> {
let mut list: SchemeList = SchemeList::new();
ROOT_SCHEME_ID.store(list.insert(Box::new(*b""), Arc::new(Box::new(RootScheme::new()))).expect("failed to insert root scheme"), Ordering::SeqCst);
DEBUG_SCHEME_ID.store(list.insert(Box::new(*b"debug"), Arc::new(Box::new(DebugScheme))).expect("failed to insert debug scheme"), Ordering::SeqCst);
list.insert(Box::new(*b"event"), Arc::new(Box::new(EventScheme::new()))).expect("failed to insert event scheme");
list.insert(Box::new(*b"env"), Arc::new(Box::new(EnvScheme::new()))).expect("failed to insert env scheme");
list.insert(Box::new(*b"initfs"), Arc::new(Box::new(InitFsScheme::new()))).expect("failed to insert initfs scheme");
IRQ_SCHEME_ID.store(list.insert(Box::new(*b"irq"), Arc::new(Box::new(IrqScheme))).expect("failed to insert irq scheme"), Ordering::SeqCst);
list.insert(Box::new(*b"null"), Arc::new(Box::new(NullScheme))).expect("failed to insert null scheme");
PIPE_SCHEME_ID.store(list.insert(Box::new(*b"pipe"), Arc::new(Box::new(PipeScheme))).expect("failed to insert pipe scheme"), Ordering::SeqCst);
list.insert(Box::new(*b"sys"), Arc::new(Box::new(SysScheme::new()))).expect("failed to insert sys scheme");
list.insert(Box::new(*b"zero"), Arc::new(Box::new(ZeroScheme))).expect("failed to insert zero scheme");
RwLock::new(list)
}
/// Get the global schemes list, const
pub fn schemes() -> RwLockReadGuard<'static, SchemeList> {
SCHEMES.call_once(init_schemes).read()
}
/// Get the global schemes list, mutable
pub fn schemes_mut() -> RwLockWriteGuard<'static, SchemeList> {
SCHEMES.call_once(init_schemes).write()
}
| {
return Err(Error::new(EEXIST));
} | conditional_block |
issue-60925.rs | // build-fail
// revisions: legacy v0
//[legacy]compile-flags: -Z symbol-mangling-version=legacy
//[v0]compile-flags: -Z symbol-mangling-version=v0
#![feature(rustc_attrs)]
// This test is the same code as in ui/issue-53912.rs but this test checks that the symbol mangling
// fix produces the correct result, whereas that test just checks that the reproduction compiles
// successfully and doesn't crash LLVM
fn dummy() {}
mod llvm {
pub(crate) struct Foo;
}
mod foo {
pub(crate) struct Foo<T>(T);
impl Foo<::llvm::Foo> {
#[rustc_symbol_name]
//[legacy]~^ ERROR symbol-name(_ZN11issue_609253foo37Foo$LT$issue_60925..llv$u6d$..Foo$GT$3foo
//[legacy]~| ERROR demangling(issue_60925::foo::Foo<issue_60925::llvm::Foo>::foo
//[legacy]~| ERROR demangling-alt(issue_60925::foo::Foo<issue_60925::llvm::Foo>::foo)
//[v0]~^^^^ ERROR symbol-name(_RNvMNtCs8dUWfuENynB_11issue_609253fooINtB2_3FooNtNtB4_4llvm3FooE3foo)
//[v0]~| ERROR demangling(<issue_60925[5fcbb46c6fac4139]::foo::Foo<issue_60925[5fcbb46c6fac4139]::llvm::Foo>>::foo)
//[v0]~| ERROR demangling-alt(<issue_60925::foo::Foo<issue_60925::llvm::Foo>>::foo)
pub(crate) fn foo() {
for _ in 0..0 {
for _ in &[::dummy()] {
::dummy();
::dummy();
::dummy();
}
}
}
}
pub(crate) fn foo() {
Foo::foo();
Foo::foo();
}
}
pub fn foo() {
foo::foo();
}
fn | () {}
| main | identifier_name |
issue-60925.rs | // build-fail
// revisions: legacy v0
//[legacy]compile-flags: -Z symbol-mangling-version=legacy
//[v0]compile-flags: -Z symbol-mangling-version=v0
#![feature(rustc_attrs)]
// This test is the same code as in ui/issue-53912.rs but this test checks that the symbol mangling
// fix produces the correct result, whereas that test just checks that the reproduction compiles
// successfully and doesn't crash LLVM
fn dummy() {}
mod llvm {
pub(crate) struct Foo;
}
mod foo {
pub(crate) struct Foo<T>(T);
impl Foo<::llvm::Foo> {
#[rustc_symbol_name]
//[legacy]~^ ERROR symbol-name(_ZN11issue_609253foo37Foo$LT$issue_60925..llv$u6d$..Foo$GT$3foo
//[legacy]~| ERROR demangling(issue_60925::foo::Foo<issue_60925::llvm::Foo>::foo
//[legacy]~| ERROR demangling-alt(issue_60925::foo::Foo<issue_60925::llvm::Foo>::foo)
//[v0]~^^^^ ERROR symbol-name(_RNvMNtCs8dUWfuENynB_11issue_609253fooINtB2_3FooNtNtB4_4llvm3FooE3foo)
//[v0]~| ERROR demangling(<issue_60925[5fcbb46c6fac4139]::foo::Foo<issue_60925[5fcbb46c6fac4139]::llvm::Foo>>::foo)
//[v0]~| ERROR demangling-alt(<issue_60925::foo::Foo<issue_60925::llvm::Foo>>::foo)
pub(crate) fn foo() {
for _ in 0..0 {
for _ in &[::dummy()] {
::dummy();
::dummy();
::dummy();
}
}
}
}
pub(crate) fn foo() {
Foo::foo();
Foo::foo();
}
}
pub fn foo() |
fn main() {}
| {
foo::foo();
} | identifier_body |
issue-60925.rs | // build-fail
// revisions: legacy v0
//[legacy]compile-flags: -Z symbol-mangling-version=legacy | #![feature(rustc_attrs)]
// This test is the same code as in ui/issue-53912.rs but this test checks that the symbol mangling
// fix produces the correct result, whereas that test just checks that the reproduction compiles
// successfully and doesn't crash LLVM
fn dummy() {}
mod llvm {
pub(crate) struct Foo;
}
mod foo {
pub(crate) struct Foo<T>(T);
impl Foo<::llvm::Foo> {
#[rustc_symbol_name]
//[legacy]~^ ERROR symbol-name(_ZN11issue_609253foo37Foo$LT$issue_60925..llv$u6d$..Foo$GT$3foo
//[legacy]~| ERROR demangling(issue_60925::foo::Foo<issue_60925::llvm::Foo>::foo
//[legacy]~| ERROR demangling-alt(issue_60925::foo::Foo<issue_60925::llvm::Foo>::foo)
//[v0]~^^^^ ERROR symbol-name(_RNvMNtCs8dUWfuENynB_11issue_609253fooINtB2_3FooNtNtB4_4llvm3FooE3foo)
//[v0]~| ERROR demangling(<issue_60925[5fcbb46c6fac4139]::foo::Foo<issue_60925[5fcbb46c6fac4139]::llvm::Foo>>::foo)
//[v0]~| ERROR demangling-alt(<issue_60925::foo::Foo<issue_60925::llvm::Foo>>::foo)
pub(crate) fn foo() {
for _ in 0..0 {
for _ in &[::dummy()] {
::dummy();
::dummy();
::dummy();
}
}
}
}
pub(crate) fn foo() {
Foo::foo();
Foo::foo();
}
}
pub fn foo() {
foo::foo();
}
fn main() {} | //[v0]compile-flags: -Z symbol-mangling-version=v0
| random_line_split |
incoming.rs | use ::std::sync::{Arc, RwLock, Mutex};
use ::std::io::ErrorKind;
use ::jedi::{self, Value};
use ::error::{TResult, TError};
use ::sync::{SyncConfig, Syncer};
use ::sync::sync_model::{SyncModel, MemorySaver};
use ::storage::Storage;
use ::rusqlite::NO_PARAMS;
use ::api::{Api, ApiReq};
use ::messaging;
use ::models;
use ::models::protected::{Protected, Keyfinder};
use ::models::model::Model;
use ::models::user::User;
use ::models::keychain::KeychainEntry;
use ::models::space::Space;
use ::models::invite::Invite;
use ::models::board::Board;
use ::models::note::Note;
use ::models::file::FileData;
use ::models::sync_record::{SyncType, SyncRecord, SyncAction};
use ::turtl::Turtl;
use ::std::mem;
use ::config;
use ::util;
const SYNC_IGNORE_KEY: &'static str = "sync:incoming:ignore";
#[derive(Serialize, Deserialize, Debug)]
pub struct SyncResponseExtra {
#[serde(default)]
current_size: Option<i64>,
#[serde(default)]
max_size: Option<i64>,
}
/// Defines a struct for deserializing our incoming sync response
#[derive(Deserialize, Debug)]
struct SyncResponse {
#[serde(default)]
records: Vec<SyncRecord>,
#[serde(default)]
#[serde(deserialize_with = "::util::ser::str_i64_converter::deserialize")]
sync_id: i64,
/// extra data returned from the sync system
#[serde(default)]
extra: Option<SyncResponseExtra>,
}
struct Handlers {
user: models::user::User,
keychain: models::keychain::KeychainEntry,
space: models::space::Space,
board: models::board::Board,
note: models::note::Note,
file: models::file::FileData,
invite: models::invite::Invite,
}
/// Lets the server know why we are asking for an incoming sync.
#[derive(Debug, Serialize, PartialEq)]
enum SyncReason {
#[serde(rename = "poll")]
Poll,
#[serde(rename = "reconnect")]
Reconnect,
#[serde(rename = "initial")]
Initial,
}
/// Given a Value object with sync_ids, try to ignore the sync ids. Kids' stuff.
pub fn ignore_syncs_maybe(turtl: &Turtl, val_with_sync_ids: &Value, errtype: &str) |
/// Holds the state for data going from API -> turtl (incoming sync data),
/// including tracking which sync item's we've seen and which we haven't.
pub struct SyncIncoming {
/// Holds our sync config. Note that this is shared between the sync system
/// and the `Turtl` object in the main thread.
config: Arc<RwLock<SyncConfig>>,
/// Holds our Api object. Lets us chit chat with the Turtl server.
api: Arc<Api>,
/// Holds our user-specific db. This is mainly for persisting k/v data (such
/// as our last sync_id).
db: Arc<Mutex<Option<Storage>>>,
/// For each type we get back from an outgoing poll, defines a collection
/// that is able to handle that incoming item (for instance a "note" coming
/// from the API might get handled by the NoteCollection).
handlers: Handlers,
/// Stores whether or not we're connected. Used internally, mainly to
/// determine whether we should check sync immediate (if disconnected) or
/// long-poll (if connected).
connected: bool,
/// Stores our syn run version
run_version: i64,
}
impl SyncIncoming {
/// Create a new incoming syncer
pub fn new(config: Arc<RwLock<SyncConfig>>, api: Arc<Api>, db: Arc<Mutex<Option<Storage>>>) -> SyncIncoming {
let handlers = Handlers {
user: models::user::User::new(),
keychain: models::keychain::KeychainEntry::new(),
space: models::space::Space::new(),
board: models::board::Board::new(),
note: models::note::Note::new(),
file: models::file::FileData::new(),
invite: models::invite::Invite::new(),
};
SyncIncoming {
config: config,
api: api,
db: db,
handlers: handlers,
connected: false,
run_version: 0,
}
}
/// Get all sync ids that should be ignored on the next sync run
fn get_ignored_impl(db: &mut Storage) -> TResult<Vec<String>> {
let ignored = match db.kv_get(SYNC_IGNORE_KEY)? {
Some(x) => jedi::parse(&x)?,
None => Vec::new(),
};
Ok(ignored)
}
/// Static handler for ignoring sync items.
///
/// Tracks which sync items we should ignore on incoming. The idea is that
/// when an outgoing sync creates a note, that note will already be created
/// on our side (client side). So the outgoing sync adds the sync ids of the
/// syncs created while adding that note to the ignore list, and when the
/// incoming sync returns, it won't re-run the syncs for the items we are
/// already up-to-date on locally. Note that this is not strictly necessary
/// since the sync system should be able to handle situations like this
/// (such as double-adding a note), however it can be much more efficient
/// especially in the case of file syncing.
pub fn ignore_on_next(db: &mut Storage, sync_ids: &Vec<i64>) -> TResult<()> {
let mut ignored = SyncIncoming::get_ignored_impl(db)?;
for sync_id in sync_ids {
ignored.push(sync_id.to_string());
}
db.kv_set(SYNC_IGNORE_KEY, &jedi::stringify(&ignored)?)
}
/// Get all sync ids that should be ignored on the next sync run
fn get_ignored(&self) -> TResult<Vec<String>> {
with_db!{ db, self.db, SyncIncoming::get_ignored_impl(db) }
}
/// Clear out ignored sync ids
fn clear_ignored(&self) -> TResult<()> {
with_db!{ db, self.db, db.kv_delete(SYNC_IGNORE_KEY) }
}
/// Grab the latest changes from the API (anything after the given sync ID).
/// Also, if `poll` is true, we long-poll.
fn sync_from_api(&mut self, sync_id: &String, reason: SyncReason) -> TResult<()> {
let reason_s = util::enum_to_string(&reason)?;
let url = format!("/sync?sync_id={}&type={}", sync_id, reason_s);
let timeout = match &reason {
SyncReason::Poll => {
config::get(&["sync", "poll_timeout"]).unwrap_or(60)
}
_ => 10
};
let reqopt = ApiReq::new().timeout(timeout);
let syncres: TResult<SyncResponse> = self.api.get(url.as_str())?.call_opt(reqopt);
// ^ this call can take a while. if sync got disabled while it was
// taking its sweet time, then bail on the result.
if!self.is_enabled() { return Ok(()); }
// if we have a timeout just return Ok(()) (the sync system is built to
// timeout if no response is received)
let syncdata = match syncres {
Ok(x) => x,
Err(e) => {
let e = e.shed();
match e {
TError::Io(io) => {
match io.kind() {
ErrorKind::TimedOut => return Ok(()),
// android throws this at us quite often, would
// be nice to know why, but for now going to just
// ignore it.
ErrorKind::WouldBlock => return Ok(()),
_ => {
info!("SyncIncoming.sync_from_api() -- unknown IO error kind: {:?}", io.kind());
self.set_connected(false);
return TErr!(TError::Io(io));
}
}
}
TError::Api(status, msg) => {
self.set_connected(false);
return TErr!(TError::Api(status, msg));
}
_ => return Err(e),
}
},
};
self.set_connected(true);
self.update_local_db_from_api_sync(syncdata, reason!= SyncReason::Poll)
}
/// Load the user's entire profile. The API gives us back a set of sync
/// objects, which is super handy because we can just treat them like any
/// other sync
fn load_full_profile(&mut self) -> TResult<()> {
let syncdata = self.api.get("/sync/full")?.call_opt(ApiReq::new().timeout(120))?;
self.set_connected(true);
self.update_local_db_from_api_sync(syncdata, true)
}
/// Take sync data we got from the API and update our local database with
/// it. Kewl.
fn update_local_db_from_api_sync(&self, syncdata: SyncResponse, force: bool) -> TResult<()> {
// sometimes the sync call takes a while, and it's possible we've quit
// mid-call. if this is the case, throw out our sync result.
if self.should_quit() &&!force { return Ok(()); }
// same, but with enabled
if!self.is_enabled() &&!force { return Ok(()); }
// destructure our response
let SyncResponse { sync_id, records, extra } = syncdata;
// grab sync ids we're ignoring
let ignored = self.get_ignored()?;
let mut ignore_count = 0;
// filter out ignored records
let mut records = records
.into_iter()
.filter(|rec| {
match rec.id() {
Some(id) => {
if ignored.contains(id) {
debug!("SyncIncoming.update_local_db_from_api_sync() -- ignoring {}", id);
ignore_count += 1;
false
} else {
true
}
}
None => { true }
}
})
.collect::<Vec<_>>();
info!("SyncIncoming.update_local_db_from_api_sync() -- ignored {} incoming syncs", ignore_count);
with_db!{ db, self.db,
// start a transaction. running incoming sync is all or nothing.
db.conn.execute("BEGIN TRANSACTION", NO_PARAMS)?;
for rec in &mut records {
self.run_sync_item(db, rec)?;
}
// save our sync id
db.kv_set("sync_id", &sync_id.to_string())?;
// ok, commit
db.conn.execute("COMMIT TRANSACTION", NO_PARAMS)?;
}
// send our incoming syncs into a queue that the Turtl/dispatch thread
// can read and process. The purpose is to run MemorySaver for the syncs
// which can only happen if we have access to Turtl, which we DO NOT
// at this particular juncture.
let sync_incoming_queue = {
let conf = self.get_config();
let sync_config_guard = lockr!(conf);
sync_config_guard.incoming_sync.clone()
};
// queue em
for rec in records { sync_incoming_queue.push(rec); }
// this is what tells our dispatch thread to load the queued incoming
// syncs and process them
messaging::app_event("sync:incoming", &())?;
// if we have extra sync data, send it off to the ui
if let Some(extra) = extra.as_ref() {
messaging::ui_event("sync:incoming:extra", extra)?;
}
// clear out the sync ignore list
match self.clear_ignored() {
Ok(_) => {},
Err(e) => error!("SyncIncoming.update_local_db_from_api_sync() -- error clearing out ignored syncs (but continue because it's not really a big deal): {}", e),
}
Ok(())
}
/// Sync an individual incoming sync item to our DB.
fn run_sync_item(&self, db: &mut Storage, sync_item: &mut SyncRecord) -> TResult<()> {
// check if we have missing data, and if so, if it's on purpose
if sync_item.data.is_none() {
let missing = match sync_item.missing {
Some(x) => x,
None => false,
};
if missing {
info!("SyncIncoming::run_sync_item() -- got missing item, probably an add/delete: {:?}", sync_item);
return Ok(());
} else {
return TErr!(TError::BadValue(format!("bad item: {:?}", sync_item)));
}
}
// send our sync item off to each type's respective handler. these are
// defined by the SyncModel (sync/sync_model.rs).
match sync_item.ty {
SyncType::User => self.handlers.user.incoming(db, sync_item),
SyncType::Keychain => self.handlers.keychain.incoming(db, sync_item),
SyncType::Space => self.handlers.space.incoming(db, sync_item),
SyncType::Board => self.handlers.board.incoming(db, sync_item),
SyncType::Note => self.handlers.note.incoming(db, sync_item),
SyncType::File | SyncType::FileIncoming => self.handlers.file.incoming(db, sync_item),
SyncType::Invite => self.handlers.invite.incoming(db, sync_item),
SyncType::FileOutgoing => Ok(()),
}?;
Ok(())
}
fn set_connected(&mut self, yesno: bool) {
self.connected = yesno;
self.connected(yesno);
}
}
impl Syncer for SyncIncoming {
fn get_name(&self) -> &'static str {
"incoming"
}
fn get_config(&self) -> Arc<RwLock<SyncConfig>> {
self.config.clone()
}
fn set_run_version(&mut self, run_version: i64) {
self.run_version = run_version;
}
fn get_run_version(&self) -> i64 {
self.run_version
}
fn init(&mut self) -> TResult<()> {
let sync_id = with_db!{ db, self.db, db.kv_get("sync_id") }?;
let skip_init = {
let config_guard = lockr!(self.config);
config_guard.skip_api_init
};
let res = if!skip_init {
match sync_id {
// we have a sync id! grab the latest changes from the API
Some(ref x) => self.sync_from_api(x, SyncReason::Initial),
// no sync id ='[ ='[ ='[...instead grab the full profile
None => self.load_full_profile(),
}
} else {
Ok(())
};
res
}
fn run_sync(&mut self) -> TResult<()> {
let sync_id = with_db!{ db, self.db, db.kv_get("sync_id") }?;
// note that when syncing changes from the server, we only poll if we
// are currently connected. this way, if we DO get a connection back
// after being previously disconnected, we can update our state
// immediately instead of waiting 60s or w/e until the sync goes through
let reason = if self.connected { SyncReason::Poll } else { SyncReason::Reconnect };
let res = match sync_id {
Some(ref x) => self.sync_from_api(x, reason),
None => return TErr!(TError::MissingData(String::from("no sync_id present"))),
};
res
}
}
/// Grabs sync records off our Turtl.incoming_sync queue (sent to us from our
/// incoming sync thread). It's important to know that this function runs with
/// access to the Turtl data as one of the main dispatch threads, NOT in the
/// incoming sync thread.
///
/// Essentially, this is what's responsible for running MemorySaver for our
/// incoming syncs.
pub fn process_incoming_sync(turtl: &Turtl) -> TResult<()> {
let sync_incoming_queue = {
let sync_config_guard = lockr!(turtl.sync_config);
sync_config_guard.incoming_sync.clone()
};
loop {
let sync_incoming_lock = turtl.incoming_sync_lock.lock();
let sync_item = match sync_incoming_queue.try_pop() {
Some(x) => x,
None => break,
};
fn mem_save<T>(turtl: &Turtl, mut sync_item: SyncRecord) -> TResult<()>
where T: Protected + MemorySaver + Keyfinder
{
let model = if &sync_item.action == &SyncAction::Delete {
let mut model: T = Default::default();
model.set_id(sync_item.item_id.clone());
model
} else {
let mut data = Value::Null;
match sync_item.data.as_mut() {
Some(x) => mem::swap(&mut data, x),
None => return TErr!(TError::MissingData(format!("sync item missing `data` field."))),
}
let mut model: T = jedi::from_val(data)?;
if model.should_deserialize_on_mem_update() {
turtl.find_model_key(&mut model)?;
model.deserialize()?;
}
model
};
model.run_mem_update(turtl, sync_item.action.clone())?;
Ok(())
}
match sync_item.ty.clone() {
SyncType::User => mem_save::<User>(turtl, sync_item)?,
SyncType::Keychain => mem_save::<KeychainEntry>(turtl, sync_item)?,
SyncType::Space => mem_save::<Space>(turtl, sync_item)?,
SyncType::Board => mem_save::<Board>(turtl, sync_item)?,
SyncType::Note => mem_save::<Note>(turtl, sync_item)?,
SyncType::File => mem_save::<FileData>(turtl, sync_item)?,
SyncType::Invite => mem_save::<Invite>(turtl, sync_item)?,
_ => (),
}
drop(sync_incoming_lock);
}
Ok(())
}
| {
match jedi::get_opt::<Vec<i64>>(&["sync_ids"], val_with_sync_ids) {
Some(x) => {
let mut db_guard = lock!(turtl.db);
if db_guard.is_some() {
match SyncIncoming::ignore_on_next(db_guard.as_mut().expect("turtl::sync_incoming::ignore_syncs_maybe() -- db is None"), &x) {
Ok(..) => {},
Err(e) => warn!("{} -- error ignoring sync items: {}", errtype, e),
}
}
}
None => {}
}
} | identifier_body |
incoming.rs | use ::std::sync::{Arc, RwLock, Mutex};
use ::std::io::ErrorKind;
use ::jedi::{self, Value};
use ::error::{TResult, TError};
use ::sync::{SyncConfig, Syncer};
use ::sync::sync_model::{SyncModel, MemorySaver};
use ::storage::Storage;
use ::rusqlite::NO_PARAMS;
use ::api::{Api, ApiReq};
use ::messaging;
use ::models;
use ::models::protected::{Protected, Keyfinder};
use ::models::model::Model;
use ::models::user::User;
use ::models::keychain::KeychainEntry;
use ::models::space::Space;
use ::models::invite::Invite;
use ::models::board::Board;
use ::models::note::Note;
use ::models::file::FileData;
use ::models::sync_record::{SyncType, SyncRecord, SyncAction};
use ::turtl::Turtl;
use ::std::mem;
use ::config;
use ::util;
const SYNC_IGNORE_KEY: &'static str = "sync:incoming:ignore";
#[derive(Serialize, Deserialize, Debug)]
pub struct SyncResponseExtra {
#[serde(default)]
current_size: Option<i64>,
#[serde(default)]
max_size: Option<i64>,
}
/// Defines a struct for deserializing our incoming sync response
#[derive(Deserialize, Debug)]
struct SyncResponse {
#[serde(default)]
records: Vec<SyncRecord>,
#[serde(default)]
#[serde(deserialize_with = "::util::ser::str_i64_converter::deserialize")]
sync_id: i64,
/// extra data returned from the sync system
#[serde(default)]
extra: Option<SyncResponseExtra>,
}
struct Handlers {
user: models::user::User,
keychain: models::keychain::KeychainEntry,
space: models::space::Space,
board: models::board::Board,
note: models::note::Note,
file: models::file::FileData,
invite: models::invite::Invite,
}
/// Lets the server know why we are asking for an incoming sync.
#[derive(Debug, Serialize, PartialEq)]
enum SyncReason {
#[serde(rename = "poll")]
Poll,
#[serde(rename = "reconnect")]
Reconnect,
#[serde(rename = "initial")]
Initial,
}
/// Given a Value object with sync_ids, try to ignore the sync ids. Kids' stuff.
pub fn ignore_syncs_maybe(turtl: &Turtl, val_with_sync_ids: &Value, errtype: &str) {
match jedi::get_opt::<Vec<i64>>(&["sync_ids"], val_with_sync_ids) {
Some(x) => {
let mut db_guard = lock!(turtl.db);
if db_guard.is_some() {
match SyncIncoming::ignore_on_next(db_guard.as_mut().expect("turtl::sync_incoming::ignore_syncs_maybe() -- db is None"), &x) {
Ok(..) => {},
Err(e) => warn!("{} -- error ignoring sync items: {}", errtype, e),
}
}
}
None => {}
}
}
/// Holds the state for data going from API -> turtl (incoming sync data),
/// including tracking which sync item's we've seen and which we haven't.
pub struct SyncIncoming {
/// Holds our sync config. Note that this is shared between the sync system
/// and the `Turtl` object in the main thread.
config: Arc<RwLock<SyncConfig>>,
/// Holds our Api object. Lets us chit chat with the Turtl server.
api: Arc<Api>,
/// Holds our user-specific db. This is mainly for persisting k/v data (such
/// as our last sync_id).
db: Arc<Mutex<Option<Storage>>>,
/// For each type we get back from an outgoing poll, defines a collection
/// that is able to handle that incoming item (for instance a "note" coming
/// from the API might get handled by the NoteCollection).
handlers: Handlers,
/// Stores whether or not we're connected. Used internally, mainly to
/// determine whether we should check sync immediate (if disconnected) or
/// long-poll (if connected).
connected: bool,
/// Stores our syn run version
run_version: i64,
}
impl SyncIncoming {
/// Create a new incoming syncer
pub fn new(config: Arc<RwLock<SyncConfig>>, api: Arc<Api>, db: Arc<Mutex<Option<Storage>>>) -> SyncIncoming {
let handlers = Handlers {
user: models::user::User::new(),
keychain: models::keychain::KeychainEntry::new(),
space: models::space::Space::new(),
board: models::board::Board::new(),
note: models::note::Note::new(),
file: models::file::FileData::new(),
invite: models::invite::Invite::new(),
};
SyncIncoming {
config: config,
api: api,
db: db,
handlers: handlers,
connected: false,
run_version: 0,
}
}
/// Get all sync ids that should be ignored on the next sync run
fn get_ignored_impl(db: &mut Storage) -> TResult<Vec<String>> {
let ignored = match db.kv_get(SYNC_IGNORE_KEY)? {
Some(x) => jedi::parse(&x)?,
None => Vec::new(),
};
Ok(ignored)
}
/// Static handler for ignoring sync items.
///
/// Tracks which sync items we should ignore on incoming. The idea is that
/// when an outgoing sync creates a note, that note will already be created
/// on our side (client side). So the outgoing sync adds the sync ids of the
/// syncs created while adding that note to the ignore list, and when the
/// incoming sync returns, it won't re-run the syncs for the items we are
/// already up-to-date on locally. Note that this is not strictly necessary
/// since the sync system should be able to handle situations like this
/// (such as double-adding a note), however it can be much more efficient
/// especially in the case of file syncing.
pub fn ignore_on_next(db: &mut Storage, sync_ids: &Vec<i64>) -> TResult<()> {
let mut ignored = SyncIncoming::get_ignored_impl(db)?;
for sync_id in sync_ids {
ignored.push(sync_id.to_string());
}
db.kv_set(SYNC_IGNORE_KEY, &jedi::stringify(&ignored)?)
}
/// Get all sync ids that should be ignored on the next sync run
fn get_ignored(&self) -> TResult<Vec<String>> {
with_db!{ db, self.db, SyncIncoming::get_ignored_impl(db) }
}
/// Clear out ignored sync ids
fn clear_ignored(&self) -> TResult<()> {
with_db!{ db, self.db, db.kv_delete(SYNC_IGNORE_KEY) }
}
/// Grab the latest changes from the API (anything after the given sync ID).
/// Also, if `poll` is true, we long-poll.
fn sync_from_api(&mut self, sync_id: &String, reason: SyncReason) -> TResult<()> {
let reason_s = util::enum_to_string(&reason)?;
let url = format!("/sync?sync_id={}&type={}", sync_id, reason_s);
let timeout = match &reason {
SyncReason::Poll => {
config::get(&["sync", "poll_timeout"]).unwrap_or(60)
}
_ => 10
};
let reqopt = ApiReq::new().timeout(timeout);
let syncres: TResult<SyncResponse> = self.api.get(url.as_str())?.call_opt(reqopt);
// ^ this call can take a while. if sync got disabled while it was
// taking its sweet time, then bail on the result.
if!self.is_enabled() { return Ok(()); }
// if we have a timeout just return Ok(()) (the sync system is built to
// timeout if no response is received)
let syncdata = match syncres {
Ok(x) => x,
Err(e) => {
let e = e.shed();
match e {
TError::Io(io) => {
match io.kind() {
ErrorKind::TimedOut => return Ok(()),
// android throws this at us quite often, would
// be nice to know why, but for now going to just
// ignore it.
ErrorKind::WouldBlock => return Ok(()),
_ => {
info!("SyncIncoming.sync_from_api() -- unknown IO error kind: {:?}", io.kind());
self.set_connected(false);
return TErr!(TError::Io(io));
}
}
}
TError::Api(status, msg) => {
self.set_connected(false);
return TErr!(TError::Api(status, msg));
}
_ => return Err(e),
}
},
};
self.set_connected(true);
self.update_local_db_from_api_sync(syncdata, reason!= SyncReason::Poll)
}
/// Load the user's entire profile. The API gives us back a set of sync
/// objects, which is super handy because we can just treat them like any
/// other sync
fn load_full_profile(&mut self) -> TResult<()> {
let syncdata = self.api.get("/sync/full")?.call_opt(ApiReq::new().timeout(120))?;
self.set_connected(true);
self.update_local_db_from_api_sync(syncdata, true)
}
/// Take sync data we got from the API and update our local database with
/// it. Kewl.
fn update_local_db_from_api_sync(&self, syncdata: SyncResponse, force: bool) -> TResult<()> {
// sometimes the sync call takes a while, and it's possible we've quit
// mid-call. if this is the case, throw out our sync result.
if self.should_quit() &&!force { return Ok(()); }
// same, but with enabled
if!self.is_enabled() &&!force { return Ok(()); }
// destructure our response
let SyncResponse { sync_id, records, extra } = syncdata;
// grab sync ids we're ignoring
let ignored = self.get_ignored()?;
let mut ignore_count = 0;
// filter out ignored records
let mut records = records
.into_iter()
.filter(|rec| {
match rec.id() {
Some(id) => {
if ignored.contains(id) {
debug!("SyncIncoming.update_local_db_from_api_sync() -- ignoring {}", id);
ignore_count += 1;
false
} else {
true
}
}
None => { true }
}
})
.collect::<Vec<_>>();
info!("SyncIncoming.update_local_db_from_api_sync() -- ignored {} incoming syncs", ignore_count);
with_db!{ db, self.db,
// start a transaction. running incoming sync is all or nothing.
db.conn.execute("BEGIN TRANSACTION", NO_PARAMS)?;
for rec in &mut records {
self.run_sync_item(db, rec)?;
}
// save our sync id
db.kv_set("sync_id", &sync_id.to_string())?;
// ok, commit
db.conn.execute("COMMIT TRANSACTION", NO_PARAMS)?;
}
// send our incoming syncs into a queue that the Turtl/dispatch thread
// can read and process. The purpose is to run MemorySaver for the syncs
// which can only happen if we have access to Turtl, which we DO NOT
// at this particular juncture.
let sync_incoming_queue = {
let conf = self.get_config();
let sync_config_guard = lockr!(conf);
sync_config_guard.incoming_sync.clone()
};
// queue em
for rec in records { sync_incoming_queue.push(rec); }
// this is what tells our dispatch thread to load the queued incoming
// syncs and process them
messaging::app_event("sync:incoming", &())?;
// if we have extra sync data, send it off to the ui
if let Some(extra) = extra.as_ref() {
messaging::ui_event("sync:incoming:extra", extra)?;
}
// clear out the sync ignore list
match self.clear_ignored() {
Ok(_) => {},
Err(e) => error!("SyncIncoming.update_local_db_from_api_sync() -- error clearing out ignored syncs (but continue because it's not really a big deal): {}", e),
}
Ok(())
}
/// Sync an individual incoming sync item to our DB.
fn run_sync_item(&self, db: &mut Storage, sync_item: &mut SyncRecord) -> TResult<()> {
// check if we have missing data, and if so, if it's on purpose
if sync_item.data.is_none() {
let missing = match sync_item.missing {
Some(x) => x,
None => false,
};
if missing {
info!("SyncIncoming::run_sync_item() -- got missing item, probably an add/delete: {:?}", sync_item);
return Ok(());
} else {
return TErr!(TError::BadValue(format!("bad item: {:?}", sync_item)));
}
}
// send our sync item off to each type's respective handler. these are
// defined by the SyncModel (sync/sync_model.rs).
match sync_item.ty {
SyncType::User => self.handlers.user.incoming(db, sync_item),
SyncType::Keychain => self.handlers.keychain.incoming(db, sync_item),
SyncType::Space => self.handlers.space.incoming(db, sync_item),
SyncType::Board => self.handlers.board.incoming(db, sync_item),
SyncType::Note => self.handlers.note.incoming(db, sync_item),
SyncType::File | SyncType::FileIncoming => self.handlers.file.incoming(db, sync_item),
SyncType::Invite => self.handlers.invite.incoming(db, sync_item),
SyncType::FileOutgoing => Ok(()),
}?;
Ok(())
}
fn set_connected(&mut self, yesno: bool) {
self.connected = yesno;
self.connected(yesno);
}
}
impl Syncer for SyncIncoming {
fn get_name(&self) -> &'static str {
"incoming"
}
fn get_config(&self) -> Arc<RwLock<SyncConfig>> {
self.config.clone()
}
fn set_run_version(&mut self, run_version: i64) {
self.run_version = run_version;
}
fn get_run_version(&self) -> i64 {
self.run_version
}
fn init(&mut self) -> TResult<()> {
let sync_id = with_db!{ db, self.db, db.kv_get("sync_id") }?;
let skip_init = {
let config_guard = lockr!(self.config);
config_guard.skip_api_init
};
let res = if!skip_init {
match sync_id {
// we have a sync id! grab the latest changes from the API
Some(ref x) => self.sync_from_api(x, SyncReason::Initial),
// no sync id ='[ ='[ ='[...instead grab the full profile
None => self.load_full_profile(),
}
} else {
Ok(())
};
res
}
fn run_sync(&mut self) -> TResult<()> {
let sync_id = with_db!{ db, self.db, db.kv_get("sync_id") }?;
// note that when syncing changes from the server, we only poll if we
// are currently connected. this way, if we DO get a connection back
// after being previously disconnected, we can update our state
// immediately instead of waiting 60s or w/e until the sync goes through
let reason = if self.connected { SyncReason::Poll } else { SyncReason::Reconnect };
let res = match sync_id {
Some(ref x) => self.sync_from_api(x, reason),
None => return TErr!(TError::MissingData(String::from("no sync_id present"))),
};
res
}
}
/// Grabs sync records off our Turtl.incoming_sync queue (sent to us from our
/// incoming sync thread). It's important to know that this function runs with
/// access to the Turtl data as one of the main dispatch threads, NOT in the
/// incoming sync thread.
///
/// Essentially, this is what's responsible for running MemorySaver for our
/// incoming syncs.
pub fn process_incoming_sync(turtl: &Turtl) -> TResult<()> {
let sync_incoming_queue = {
let sync_config_guard = lockr!(turtl.sync_config);
sync_config_guard.incoming_sync.clone()
};
loop {
let sync_incoming_lock = turtl.incoming_sync_lock.lock();
let sync_item = match sync_incoming_queue.try_pop() {
Some(x) => x,
None => break,
};
fn mem_save<T>(turtl: &Turtl, mut sync_item: SyncRecord) -> TResult<()>
where T: Protected + MemorySaver + Keyfinder
{
let model = if &sync_item.action == &SyncAction::Delete {
let mut model: T = Default::default();
model.set_id(sync_item.item_id.clone());
model
} else {
let mut data = Value::Null;
match sync_item.data.as_mut() {
Some(x) => mem::swap(&mut data, x),
None => return TErr!(TError::MissingData(format!("sync item missing `data` field."))),
}
let mut model: T = jedi::from_val(data)?;
if model.should_deserialize_on_mem_update() { | model
};
model.run_mem_update(turtl, sync_item.action.clone())?;
Ok(())
}
match sync_item.ty.clone() {
SyncType::User => mem_save::<User>(turtl, sync_item)?,
SyncType::Keychain => mem_save::<KeychainEntry>(turtl, sync_item)?,
SyncType::Space => mem_save::<Space>(turtl, sync_item)?,
SyncType::Board => mem_save::<Board>(turtl, sync_item)?,
SyncType::Note => mem_save::<Note>(turtl, sync_item)?,
SyncType::File => mem_save::<FileData>(turtl, sync_item)?,
SyncType::Invite => mem_save::<Invite>(turtl, sync_item)?,
_ => (),
}
drop(sync_incoming_lock);
}
Ok(())
} | turtl.find_model_key(&mut model)?;
model.deserialize()?;
} | random_line_split |
incoming.rs | use ::std::sync::{Arc, RwLock, Mutex};
use ::std::io::ErrorKind;
use ::jedi::{self, Value};
use ::error::{TResult, TError};
use ::sync::{SyncConfig, Syncer};
use ::sync::sync_model::{SyncModel, MemorySaver};
use ::storage::Storage;
use ::rusqlite::NO_PARAMS;
use ::api::{Api, ApiReq};
use ::messaging;
use ::models;
use ::models::protected::{Protected, Keyfinder};
use ::models::model::Model;
use ::models::user::User;
use ::models::keychain::KeychainEntry;
use ::models::space::Space;
use ::models::invite::Invite;
use ::models::board::Board;
use ::models::note::Note;
use ::models::file::FileData;
use ::models::sync_record::{SyncType, SyncRecord, SyncAction};
use ::turtl::Turtl;
use ::std::mem;
use ::config;
use ::util;
const SYNC_IGNORE_KEY: &'static str = "sync:incoming:ignore";
#[derive(Serialize, Deserialize, Debug)]
pub struct SyncResponseExtra {
#[serde(default)]
current_size: Option<i64>,
#[serde(default)]
max_size: Option<i64>,
}
/// Defines a struct for deserializing our incoming sync response
#[derive(Deserialize, Debug)]
struct SyncResponse {
#[serde(default)]
records: Vec<SyncRecord>,
#[serde(default)]
#[serde(deserialize_with = "::util::ser::str_i64_converter::deserialize")]
sync_id: i64,
/// extra data returned from the sync system
#[serde(default)]
extra: Option<SyncResponseExtra>,
}
struct Handlers {
user: models::user::User,
keychain: models::keychain::KeychainEntry,
space: models::space::Space,
board: models::board::Board,
note: models::note::Note,
file: models::file::FileData,
invite: models::invite::Invite,
}
/// Lets the server know why we are asking for an incoming sync.
#[derive(Debug, Serialize, PartialEq)]
enum SyncReason {
#[serde(rename = "poll")]
Poll,
#[serde(rename = "reconnect")]
Reconnect,
#[serde(rename = "initial")]
Initial,
}
/// Given a Value object with sync_ids, try to ignore the sync ids. Kids' stuff.
pub fn ignore_syncs_maybe(turtl: &Turtl, val_with_sync_ids: &Value, errtype: &str) {
match jedi::get_opt::<Vec<i64>>(&["sync_ids"], val_with_sync_ids) {
Some(x) => {
let mut db_guard = lock!(turtl.db);
if db_guard.is_some() {
match SyncIncoming::ignore_on_next(db_guard.as_mut().expect("turtl::sync_incoming::ignore_syncs_maybe() -- db is None"), &x) {
Ok(..) => {},
Err(e) => warn!("{} -- error ignoring sync items: {}", errtype, e),
}
}
}
None => {}
}
}
/// Holds the state for data going from API -> turtl (incoming sync data),
/// including tracking which sync item's we've seen and which we haven't.
pub struct SyncIncoming {
/// Holds our sync config. Note that this is shared between the sync system
/// and the `Turtl` object in the main thread.
config: Arc<RwLock<SyncConfig>>,
/// Holds our Api object. Lets us chit chat with the Turtl server.
api: Arc<Api>,
/// Holds our user-specific db. This is mainly for persisting k/v data (such
/// as our last sync_id).
db: Arc<Mutex<Option<Storage>>>,
/// For each type we get back from an outgoing poll, defines a collection
/// that is able to handle that incoming item (for instance a "note" coming
/// from the API might get handled by the NoteCollection).
handlers: Handlers,
/// Stores whether or not we're connected. Used internally, mainly to
/// determine whether we should check sync immediate (if disconnected) or
/// long-poll (if connected).
connected: bool,
/// Stores our syn run version
run_version: i64,
}
impl SyncIncoming {
/// Create a new incoming syncer
pub fn new(config: Arc<RwLock<SyncConfig>>, api: Arc<Api>, db: Arc<Mutex<Option<Storage>>>) -> SyncIncoming {
let handlers = Handlers {
user: models::user::User::new(),
keychain: models::keychain::KeychainEntry::new(),
space: models::space::Space::new(),
board: models::board::Board::new(),
note: models::note::Note::new(),
file: models::file::FileData::new(),
invite: models::invite::Invite::new(),
};
SyncIncoming {
config: config,
api: api,
db: db,
handlers: handlers,
connected: false,
run_version: 0,
}
}
/// Get all sync ids that should be ignored on the next sync run
fn get_ignored_impl(db: &mut Storage) -> TResult<Vec<String>> {
let ignored = match db.kv_get(SYNC_IGNORE_KEY)? {
Some(x) => jedi::parse(&x)?,
None => Vec::new(),
};
Ok(ignored)
}
/// Static handler for ignoring sync items.
///
/// Tracks which sync items we should ignore on incoming. The idea is that
/// when an outgoing sync creates a note, that note will already be created
/// on our side (client side). So the outgoing sync adds the sync ids of the
/// syncs created while adding that note to the ignore list, and when the
/// incoming sync returns, it won't re-run the syncs for the items we are
/// already up-to-date on locally. Note that this is not strictly necessary
/// since the sync system should be able to handle situations like this
/// (such as double-adding a note), however it can be much more efficient
/// especially in the case of file syncing.
pub fn ignore_on_next(db: &mut Storage, sync_ids: &Vec<i64>) -> TResult<()> {
let mut ignored = SyncIncoming::get_ignored_impl(db)?;
for sync_id in sync_ids {
ignored.push(sync_id.to_string());
}
db.kv_set(SYNC_IGNORE_KEY, &jedi::stringify(&ignored)?)
}
/// Get all sync ids that should be ignored on the next sync run
fn get_ignored(&self) -> TResult<Vec<String>> {
with_db!{ db, self.db, SyncIncoming::get_ignored_impl(db) }
}
/// Clear out ignored sync ids
fn clear_ignored(&self) -> TResult<()> {
with_db!{ db, self.db, db.kv_delete(SYNC_IGNORE_KEY) }
}
/// Grab the latest changes from the API (anything after the given sync ID).
/// Also, if `poll` is true, we long-poll.
fn sync_from_api(&mut self, sync_id: &String, reason: SyncReason) -> TResult<()> {
let reason_s = util::enum_to_string(&reason)?;
let url = format!("/sync?sync_id={}&type={}", sync_id, reason_s);
let timeout = match &reason {
SyncReason::Poll => {
config::get(&["sync", "poll_timeout"]).unwrap_or(60)
}
_ => 10
};
let reqopt = ApiReq::new().timeout(timeout);
let syncres: TResult<SyncResponse> = self.api.get(url.as_str())?.call_opt(reqopt);
// ^ this call can take a while. if sync got disabled while it was
// taking its sweet time, then bail on the result.
if!self.is_enabled() { return Ok(()); }
// if we have a timeout just return Ok(()) (the sync system is built to
// timeout if no response is received)
let syncdata = match syncres {
Ok(x) => x,
Err(e) => {
let e = e.shed();
match e {
TError::Io(io) => {
match io.kind() {
ErrorKind::TimedOut => return Ok(()),
// android throws this at us quite often, would
// be nice to know why, but for now going to just
// ignore it.
ErrorKind::WouldBlock => return Ok(()),
_ => {
info!("SyncIncoming.sync_from_api() -- unknown IO error kind: {:?}", io.kind());
self.set_connected(false);
return TErr!(TError::Io(io));
}
}
}
TError::Api(status, msg) => {
self.set_connected(false);
return TErr!(TError::Api(status, msg));
}
_ => return Err(e),
}
},
};
self.set_connected(true);
self.update_local_db_from_api_sync(syncdata, reason!= SyncReason::Poll)
}
/// Load the user's entire profile. The API gives us back a set of sync
/// objects, which is super handy because we can just treat them like any
/// other sync
fn load_full_profile(&mut self) -> TResult<()> {
let syncdata = self.api.get("/sync/full")?.call_opt(ApiReq::new().timeout(120))?;
self.set_connected(true);
self.update_local_db_from_api_sync(syncdata, true)
}
/// Take sync data we got from the API and update our local database with
/// it. Kewl.
fn update_local_db_from_api_sync(&self, syncdata: SyncResponse, force: bool) -> TResult<()> {
// sometimes the sync call takes a while, and it's possible we've quit
// mid-call. if this is the case, throw out our sync result.
if self.should_quit() &&!force { return Ok(()); }
// same, but with enabled
if!self.is_enabled() &&!force { return Ok(()); }
// destructure our response
let SyncResponse { sync_id, records, extra } = syncdata;
// grab sync ids we're ignoring
let ignored = self.get_ignored()?;
let mut ignore_count = 0;
// filter out ignored records
let mut records = records
.into_iter()
.filter(|rec| {
match rec.id() {
Some(id) => {
if ignored.contains(id) {
debug!("SyncIncoming.update_local_db_from_api_sync() -- ignoring {}", id);
ignore_count += 1;
false
} else {
true
}
}
None => { true }
}
})
.collect::<Vec<_>>();
info!("SyncIncoming.update_local_db_from_api_sync() -- ignored {} incoming syncs", ignore_count);
with_db!{ db, self.db,
// start a transaction. running incoming sync is all or nothing.
db.conn.execute("BEGIN TRANSACTION", NO_PARAMS)?;
for rec in &mut records {
self.run_sync_item(db, rec)?;
}
// save our sync id
db.kv_set("sync_id", &sync_id.to_string())?;
// ok, commit
db.conn.execute("COMMIT TRANSACTION", NO_PARAMS)?;
}
// send our incoming syncs into a queue that the Turtl/dispatch thread
// can read and process. The purpose is to run MemorySaver for the syncs
// which can only happen if we have access to Turtl, which we DO NOT
// at this particular juncture.
let sync_incoming_queue = {
let conf = self.get_config();
let sync_config_guard = lockr!(conf);
sync_config_guard.incoming_sync.clone()
};
// queue em
for rec in records { sync_incoming_queue.push(rec); }
// this is what tells our dispatch thread to load the queued incoming
// syncs and process them
messaging::app_event("sync:incoming", &())?;
// if we have extra sync data, send it off to the ui
if let Some(extra) = extra.as_ref() {
messaging::ui_event("sync:incoming:extra", extra)?;
}
// clear out the sync ignore list
match self.clear_ignored() {
Ok(_) => {},
Err(e) => error!("SyncIncoming.update_local_db_from_api_sync() -- error clearing out ignored syncs (but continue because it's not really a big deal): {}", e),
}
Ok(())
}
/// Sync an individual incoming sync item to our DB.
fn run_sync_item(&self, db: &mut Storage, sync_item: &mut SyncRecord) -> TResult<()> {
// check if we have missing data, and if so, if it's on purpose
if sync_item.data.is_none() {
let missing = match sync_item.missing {
Some(x) => x,
None => false,
};
if missing {
info!("SyncIncoming::run_sync_item() -- got missing item, probably an add/delete: {:?}", sync_item);
return Ok(());
} else {
return TErr!(TError::BadValue(format!("bad item: {:?}", sync_item)));
}
}
// send our sync item off to each type's respective handler. these are
// defined by the SyncModel (sync/sync_model.rs).
match sync_item.ty {
SyncType::User => self.handlers.user.incoming(db, sync_item),
SyncType::Keychain => self.handlers.keychain.incoming(db, sync_item),
SyncType::Space => self.handlers.space.incoming(db, sync_item),
SyncType::Board => self.handlers.board.incoming(db, sync_item),
SyncType::Note => self.handlers.note.incoming(db, sync_item),
SyncType::File | SyncType::FileIncoming => self.handlers.file.incoming(db, sync_item),
SyncType::Invite => self.handlers.invite.incoming(db, sync_item),
SyncType::FileOutgoing => Ok(()),
}?;
Ok(())
}
fn set_connected(&mut self, yesno: bool) {
self.connected = yesno;
self.connected(yesno);
}
}
impl Syncer for SyncIncoming {
fn get_name(&self) -> &'static str {
"incoming"
}
fn get_config(&self) -> Arc<RwLock<SyncConfig>> {
self.config.clone()
}
fn | (&mut self, run_version: i64) {
self.run_version = run_version;
}
fn get_run_version(&self) -> i64 {
self.run_version
}
fn init(&mut self) -> TResult<()> {
let sync_id = with_db!{ db, self.db, db.kv_get("sync_id") }?;
let skip_init = {
let config_guard = lockr!(self.config);
config_guard.skip_api_init
};
let res = if!skip_init {
match sync_id {
// we have a sync id! grab the latest changes from the API
Some(ref x) => self.sync_from_api(x, SyncReason::Initial),
// no sync id ='[ ='[ ='[...instead grab the full profile
None => self.load_full_profile(),
}
} else {
Ok(())
};
res
}
fn run_sync(&mut self) -> TResult<()> {
let sync_id = with_db!{ db, self.db, db.kv_get("sync_id") }?;
// note that when syncing changes from the server, we only poll if we
// are currently connected. this way, if we DO get a connection back
// after being previously disconnected, we can update our state
// immediately instead of waiting 60s or w/e until the sync goes through
let reason = if self.connected { SyncReason::Poll } else { SyncReason::Reconnect };
let res = match sync_id {
Some(ref x) => self.sync_from_api(x, reason),
None => return TErr!(TError::MissingData(String::from("no sync_id present"))),
};
res
}
}
/// Grabs sync records off our Turtl.incoming_sync queue (sent to us from our
/// incoming sync thread). It's important to know that this function runs with
/// access to the Turtl data as one of the main dispatch threads, NOT in the
/// incoming sync thread.
///
/// Essentially, this is what's responsible for running MemorySaver for our
/// incoming syncs.
pub fn process_incoming_sync(turtl: &Turtl) -> TResult<()> {
let sync_incoming_queue = {
let sync_config_guard = lockr!(turtl.sync_config);
sync_config_guard.incoming_sync.clone()
};
loop {
let sync_incoming_lock = turtl.incoming_sync_lock.lock();
let sync_item = match sync_incoming_queue.try_pop() {
Some(x) => x,
None => break,
};
fn mem_save<T>(turtl: &Turtl, mut sync_item: SyncRecord) -> TResult<()>
where T: Protected + MemorySaver + Keyfinder
{
let model = if &sync_item.action == &SyncAction::Delete {
let mut model: T = Default::default();
model.set_id(sync_item.item_id.clone());
model
} else {
let mut data = Value::Null;
match sync_item.data.as_mut() {
Some(x) => mem::swap(&mut data, x),
None => return TErr!(TError::MissingData(format!("sync item missing `data` field."))),
}
let mut model: T = jedi::from_val(data)?;
if model.should_deserialize_on_mem_update() {
turtl.find_model_key(&mut model)?;
model.deserialize()?;
}
model
};
model.run_mem_update(turtl, sync_item.action.clone())?;
Ok(())
}
match sync_item.ty.clone() {
SyncType::User => mem_save::<User>(turtl, sync_item)?,
SyncType::Keychain => mem_save::<KeychainEntry>(turtl, sync_item)?,
SyncType::Space => mem_save::<Space>(turtl, sync_item)?,
SyncType::Board => mem_save::<Board>(turtl, sync_item)?,
SyncType::Note => mem_save::<Note>(turtl, sync_item)?,
SyncType::File => mem_save::<FileData>(turtl, sync_item)?,
SyncType::Invite => mem_save::<Invite>(turtl, sync_item)?,
_ => (),
}
drop(sync_incoming_lock);
}
Ok(())
}
| set_run_version | identifier_name |
extern-call-deep2.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.
use std::libc;
use std::task;
mod rustrt {
use std::libc;
extern {
pub fn rust_dbg_call(cb: extern "C" fn(libc::uintptr_t) -> libc::uintptr_t,
data: libc::uintptr_t)
-> libc::uintptr_t;
}
}
extern fn cb(data: libc::uintptr_t) -> libc::uintptr_t {
if data == 1u {
data
} else {
count(data - 1u) + 1u
}
}
#[fixed_stack_segment] #[inline(never)]
fn count(n: uint) -> uint {
unsafe {
info!("n = %?", n);
rustrt::rust_dbg_call(cb, n)
}
}
pub fn main() | ;
}
| {
// Make sure we're on a task with small Rust stacks (main currently
// has a large stack)
do task::spawn {
let result = count(1000u);
info!("result = %?", result);
assert_eq!(result, 1000u);
} | identifier_body |
extern-call-deep2.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.
use std::libc;
use std::task;
mod rustrt {
use std::libc;
extern {
pub fn rust_dbg_call(cb: extern "C" fn(libc::uintptr_t) -> libc::uintptr_t,
data: libc::uintptr_t)
-> libc::uintptr_t;
}
}
extern fn cb(data: libc::uintptr_t) -> libc::uintptr_t {
if data == 1u {
data
} else |
}
#[fixed_stack_segment] #[inline(never)]
fn count(n: uint) -> uint {
unsafe {
info!("n = %?", n);
rustrt::rust_dbg_call(cb, n)
}
}
pub fn main() {
// Make sure we're on a task with small Rust stacks (main currently
// has a large stack)
do task::spawn {
let result = count(1000u);
info!("result = %?", result);
assert_eq!(result, 1000u);
};
}
| {
count(data - 1u) + 1u
} | conditional_block |
extern-call-deep2.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.
use std::libc;
use std::task;
mod rustrt {
use std::libc;
extern {
pub fn rust_dbg_call(cb: extern "C" fn(libc::uintptr_t) -> libc::uintptr_t,
data: libc::uintptr_t)
-> libc::uintptr_t;
}
}
extern fn cb(data: libc::uintptr_t) -> libc::uintptr_t {
if data == 1u {
data
} else {
count(data - 1u) + 1u
}
}
#[fixed_stack_segment] #[inline(never)]
fn | (n: uint) -> uint {
unsafe {
info!("n = %?", n);
rustrt::rust_dbg_call(cb, n)
}
}
pub fn main() {
// Make sure we're on a task with small Rust stacks (main currently
// has a large stack)
do task::spawn {
let result = count(1000u);
info!("result = %?", result);
assert_eq!(result, 1000u);
};
}
| count | identifier_name |
extern-call-deep2.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.
use std::libc;
use std::task;
mod rustrt {
use std::libc;
extern {
pub fn rust_dbg_call(cb: extern "C" fn(libc::uintptr_t) -> libc::uintptr_t,
data: libc::uintptr_t)
-> libc::uintptr_t;
}
}
extern fn cb(data: libc::uintptr_t) -> libc::uintptr_t {
if data == 1u {
data
} else {
count(data - 1u) + 1u | #[fixed_stack_segment] #[inline(never)]
fn count(n: uint) -> uint {
unsafe {
info!("n = %?", n);
rustrt::rust_dbg_call(cb, n)
}
}
pub fn main() {
// Make sure we're on a task with small Rust stacks (main currently
// has a large stack)
do task::spawn {
let result = count(1000u);
info!("result = %?", result);
assert_eq!(result, 1000u);
};
} | }
}
| random_line_split |
historypack.rs | If a given entry has a parent from another file (a copy)
//! then p1node is the hgid from the other file, and copyfrom is the
//! filepath of the other file.
//!
//!.histidx
//! The index file provides a mapping from filename to the file section in
//! the histpack. In V1 it also contains sub-indexes for specific nodes
//! within each file. It consists of three parts, the fanout, the file index
//! and the hgid indexes.
//!
//! The file index is a list of index entries, sorted by filename hash (one
//! per file section in the pack). Each entry has:
//!
//! - hgid (The 20 byte hash of the filename)
//! - pack entry offset (The location of this file section in the histpack)
//! - pack content size (The on-disk length of this file section's pack
//! data)
//! - hgid index offset (The location of the file's hgid index in the index
//! file) [1]
//! - hgid index size (the on-disk length of this file's hgid index) [1]
//!
//! The fanout is a quick lookup table to reduce the number of steps for
//! bisecting the index. It is a series of 4 byte pointers to positions
//! within the index. It has 2^16 entries, which corresponds to hash
//! prefixes [00, 01, 02,..., FD, FE, FF]. Example: the pointer in slot 4F
//! points to the index position of the first revision whose hgid starts
//! with 4F. This saves log(2^16) bisect steps.
//!
//! dataidx = <fanouttable>
//! <file count: 8 byte unsigned> [1]
//! <fileindex>
//! <hgid count: 8 byte unsigned> [1]
//! [<nodeindex>,...] [1]
//! fanouttable = [<index offset: 4 byte unsigned int>,...] (2^16 entries)
//!
//! fileindex = [<file index entry>,...]
//! fileindexentry = <hgid: 20 byte>
//! <pack file section offset: 8 byte unsigned int>
//! <pack file section size: 8 byte unsigned int>
//! <hgid index offset: 4 byte unsigned int> [1]
//! <hgid index size: 4 byte unsigned int> [1]
//! nodeindex = [<hgid index entry>,...] [1]
//! filename = <filename len : 2 byte unsigned int><filename value> [1]
//! nodeindexentry = <hgid: 20 byte> [1]
//! <pack file hgid offset: 8 byte unsigned int> [1]
//!
//! ```
//! [1]: new in version 1.
use std::{
fs::File,
io::{Cursor, Read, Write},
mem::{drop, take},
path::{Path, PathBuf},
sync::Arc,
};
use anyhow::{format_err, Result};
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use memmap::{Mmap, MmapOptions};
use thiserror::Error;
use types::{HgId, Key, NodeInfo, RepoPath, RepoPathBuf};
use util::path::remove_file;
use crate::{
historyindex::HistoryIndex,
historystore::HgIdHistoryStore,
localstore::{ExtStoredPolicy, LocalStore, StoreFromPath},
repack::{Repackable, ToKeys},
sliceext::SliceExt,
types::StoreKey,
};
#[derive(Debug, Error)]
#[error("Historypack Error: {0:?}")]
struct HistoryPackError(String);
#[derive(Clone, Debug, PartialEq)]
pub enum HistoryPackVersion {
Zero,
One,
}
impl HistoryPackVersion {
fn new(value: u8) -> Result<Self> {
match value {
0 => Ok(HistoryPackVersion::Zero),
1 => Ok(HistoryPackVersion::One),
_ => Err(HistoryPackError(format!(
"invalid history pack version number '{:?}'",
value
))
.into()),
}
}
}
impl From<HistoryPackVersion> for u8 {
fn from(version: HistoryPackVersion) -> u8 {
match version {
HistoryPackVersion::Zero => 0,
HistoryPackVersion::One => 1,
}
}
}
#[derive(Debug, PartialEq)]
pub(crate) struct FileSectionHeader<'a> {
pub file_name: &'a RepoPath,
pub count: u32,
}
#[derive(Debug, PartialEq)]
pub struct HistoryEntry<'a> {
pub hgid: HgId,
pub p1: HgId,
pub p2: HgId,
pub link_hgid: HgId,
pub copy_from: Option<&'a RepoPath>,
}
fn read_slice<'a, 'b>(cur: &'a mut Cursor<&[u8]>, buf: &'b [u8], size: usize) -> Result<&'b [u8]> {
let start = cur.position() as usize;
let end = start + size;
let file_name = buf.get_err(start..end)?;
cur.set_position(end as u64);
Ok(file_name)
}
impl<'a> FileSectionHeader<'a> {
pub(crate) fn read(buf: &[u8]) -> Result<FileSectionHeader> {
let mut cur = Cursor::new(buf);
let file_name_len = cur.read_u16::<BigEndian>()? as usize;
let file_name_slice = read_slice(&mut cur, &buf, file_name_len)?;
let file_name = RepoPath::from_utf8(file_name_slice)?;
let count = cur.read_u32::<BigEndian>()?;
Ok(FileSectionHeader { file_name, count })
}
pub fn write<T: Write>(&self, writer: &mut T) -> Result<()> {
let file_name_slice = self.file_name.as_byte_slice();
writer.write_u16::<BigEndian>(file_name_slice.len() as u16)?;
writer.write_all(file_name_slice)?;
writer.write_u32::<BigEndian>(self.count)?;
Ok(())
}
}
impl<'a> HistoryEntry<'a> {
pub(crate) fn read(buf: &[u8]) -> Result<HistoryEntry> {
let mut cur = Cursor::new(buf);
let mut hgid_buf: [u8; 20] = Default::default();
// Node
cur.read_exact(&mut hgid_buf)?;
let hgid = HgId::from(&hgid_buf);
// Parents
cur.read_exact(&mut hgid_buf)?;
let p1 = HgId::from(&hgid_buf);
cur.read_exact(&mut hgid_buf)?;
let p2 = HgId::from(&hgid_buf);
// LinkNode
cur.read_exact(&mut hgid_buf)?;
let link_hgid = HgId::from(&hgid_buf);
// Copyfrom
let copy_from_len = cur.read_u16::<BigEndian>()? as usize;
let copy_from = if copy_from_len > 0 {
let slice = read_slice(&mut cur, &buf, copy_from_len)?;
Some(RepoPath::from_utf8(slice)?)
} else {
None
};
Ok(HistoryEntry {
hgid,
p1,
p2,
link_hgid,
copy_from,
})
}
pub fn write<T: Write>(
writer: &mut T,
hgid: &HgId,
p1: &HgId,
p2: &HgId,
linknode: &HgId,
copy_from: &Option<&RepoPath>,
) -> Result<()> {
writer.write_all(hgid.as_ref())?;
writer.write_all(p1.as_ref())?;
writer.write_all(p2.as_ref())?;
writer.write_all(linknode.as_ref())?;
match *copy_from {
Some(file_name) => {
let file_name_slice = file_name.as_byte_slice();
writer.write_u16::<BigEndian>(file_name_slice.len() as u16)?;
writer.write_all(file_name_slice)?;
}
None => writer.write_u16::<BigEndian>(0)?,
};
Ok(())
}
}
pub struct HistoryPack {
mmap: Mmap,
#[allow(dead_code)]
version: HistoryPackVersion,
index: HistoryIndex,
base_path: Arc<PathBuf>,
pack_path: PathBuf,
index_path: PathBuf,
}
impl HistoryPack {
pub fn new(path: impl AsRef<Path>) -> Result<Self> {
HistoryPack::with_path(path.as_ref())
}
fn with_path(path: &Path) -> Result<Self> {
let base_path = PathBuf::from(path);
let pack_path = path.with_extension("histpack");
let file = File::open(&pack_path)?;
let len = file.metadata()?.len();
if len < 1 {
return Err(format_err!(
"empty histpack '{:?}' is invalid",
path.to_str().unwrap_or("<unknown>")
));
}
let mmap = unsafe { MmapOptions::new().len(len as usize).map(&file)? };
let version = HistoryPackVersion::new(mmap[0])?;
if version!= HistoryPackVersion::One {
return Err(HistoryPackError(format!("version {:?} not supported", version)).into());
}
let index_path = path.with_extension("histidx");
Ok(HistoryPack {
mmap,
version,
index: HistoryIndex::new(&index_path)?,
base_path: Arc::new(base_path),
pack_path,
index_path,
})
}
pub fn len(&self) -> usize {
self.mmap.len()
}
pub fn base_path(&self) -> &Path {
&self.base_path
}
pub fn pack_path(&self) -> &Path {
&self.pack_path
}
pub fn index_path(&self) -> &Path {
&self.index_path
}
fn read_file_section_header(&self, offset: u64) -> Result<FileSectionHeader> {
FileSectionHeader::read(&self.mmap.as_ref().get_err(offset as usize..)?)
}
fn read_history_entry(&self, offset: u64) -> Result<HistoryEntry> {
HistoryEntry::read(&self.mmap.as_ref().get_err(offset as usize..)?)
}
fn read_node_info(&self, key: &Key, offset: u64) -> Result<NodeInfo> {
let entry = self.read_history_entry(offset)?;
assert_eq!(entry.hgid, key.hgid);
let p1 = Key::new(
match entry.copy_from {
Some(value) => value.to_owned(),
None => key.path.clone(),
},
entry.p1.clone(),
);
let p2 = Key::new(key.path.clone(), entry.p2.clone());
Ok(NodeInfo {
parents: [p1, p2],
linknode: entry.link_hgid.clone(),
})
}
}
impl HgIdHistoryStore for HistoryPack {
fn get_node_info(&self, key: &Key) -> Result<Option<NodeInfo>> {
let hgid_location = match self.index.get_hgid_entry(key)? {
None => return Ok(None),
Some(location) => location,
};
self.read_node_info(key, hgid_location.offset).map(Some)
}
fn refresh(&self) -> Result<()> {
Ok(())
}
}
impl StoreFromPath for HistoryPack {
fn from_path(path: &Path, _extstored_policy: ExtStoredPolicy) -> Result<Self> {
HistoryPack::new(path)
}
}
impl LocalStore for HistoryPack {
fn get_missing(&self, keys: &[StoreKey]) -> Result<Vec<StoreKey>> {
Ok(keys
.iter()
.filter(|k| match k {
StoreKey::HgId(k) => match self.index.get_hgid_entry(k) {
Ok(None) | Err(_) => true,
Ok(Some(_)) => false,
},
StoreKey::Content(_, _) => true,
})
.cloned()
.collect())
}
}
impl ToKeys for HistoryPack {
fn to_keys(&self) -> Vec<Result<Key>> {
HistoryPackIterator::new(self).collect()
}
}
impl Repackable for HistoryPack {
fn delete(mut self) -> Result<()> {
// On some platforms, removing a file can fail if it's still opened or mapped, let's make
// sure we close and unmap them before deletion.
let pack_path = take(&mut self.pack_path);
let index_path = take(&mut self.index_path);
drop(self);
let result1 = remove_file(&pack_path);
let result2 = remove_file(&index_path);
// Only check for errors after both have run. That way if pack_path doesn't exist,
// index_path is still deleted.
result1?;
result2?;
Ok(())
}
fn size(&self) -> u64 {
self.mmap.len() as u64
}
}
struct | <'a> {
pack: &'a HistoryPack,
offset: u64,
current_name: RepoPathBuf,
current_remaining: u32,
}
impl<'a> HistoryPackIterator<'a> {
pub fn new(pack: &'a HistoryPack) -> Self {
HistoryPackIterator {
pack,
offset: 1, // Start after the header byte
current_name: RepoPathBuf::new(),
current_remaining: 0,
}
}
}
impl<'a> Iterator for HistoryPackIterator<'a> {
type Item = Result<Key>;
fn next(&mut self) -> Option<Self::Item> {
while self.current_remaining == 0 && (self.offset as usize) < self.pack.len() {
let file_header = self.pack.read_file_section_header(self.offset);
match file_header {
Ok(header) => {
let file_name_slice = header.file_name.as_byte_slice();
self.current_name = header.file_name.to_owned();
self.current_remaining = header.count;
self.offset += 4 + 2 + file_name_slice.len() as u64;
}
Err(e) => {
self.offset = self.pack.len() as u64;
return Some(Err(e));
}
};
}
if self.offset as usize >= self.pack.len() {
return None;
}
let entry = self.pack.read_history_entry(self.offset);
self.current_remaining -= 1;
Some(match entry {
Ok(ref e) => {
self.offset += 80;
self.offset += match e.copy_from {
Some(path) => 2 + path.as_byte_slice().len() as u64,
None => 2,
};
Ok(Key::new(self.current_name.clone(), e.hgid))
}
Err(e) => {
// The entry is corrupted, and we have no way to know where the next one is
// located, let's forcibly stop the iteration.
self.offset = self.pack.len() as u64;
Err(e)
}
})
}
}
#[cfg(test)]
pub mod tests {
use super::*;
use quickcheck::quickcheck;
use rand::SeedableRng;
use rand_chacha::ChaChaRng;
use tempfile::TempDir;
use std::{
collections::HashMap,
fs::{set_permissions, File, OpenOptions},
};
use types::{testutil::*, RepoPathBuf};
use crate::{historystore::HgIdMutableHistoryStore, mutablehistorypack::MutableHistoryPack};
pub fn make_historypack(tempdir: &TempDir, nodes: &HashMap<Key, NodeInfo>) -> HistoryPack {
let mutpack = MutableHistoryPack::new(tempdir.path(), HistoryPackVersion::One);
for (ref key, ref info) in nodes.iter() {
mutpack.add(key.clone(), info.clone()).unwrap();
}
let path = &mutpack.flush().unwrap().unwrap()[0];
HistoryPack::new(&path).unwrap()
}
pub fn get_nodes(mut rng: &mut ChaChaRng) -> HashMap<Key, NodeInfo> {
let file1 = RepoPath::from_str("path").unwrap();
let file2 = RepoPath::from_str("path/file").unwrap();
let null = HgId::null_id();
let node1 = HgId::random(&mut rng);
let node2 = HgId::random(&mut rng);
let node3 = HgId::random(&mut rng);
let node4 = HgId::random(&mut rng);
let node5 = HgId::random(&mut rng);
let node6 = HgId::random(&mut rng);
let mut nodes = HashMap::new();
// Insert key 1
let key1 = Key::new(file1.to_owned(), node2.clone());
let info = NodeInfo {
parents: [
Key::new(file1.to_owned(), node1.clone()),
Key::new(file1.to_owned(), null.clone()),
],
linknode: HgId::random(&mut rng),
};
nodes.insert(key1.clone(), info.clone());
// Insert key 2
let key2 = Key::new(file2.to_owned(), node3.clone());
let info = NodeInfo {
parents: [
Key::new(file2.to_owned(), node5.clone()),
Key::new(file2.to_owned(), node6.clone()),
],
linknode: HgId::random(&mut rng),
};
nodes.insert(key2.clone(), info.clone());
// Insert key 3
let key3 = Key::new(file1.to_owned(), node4.clone());
let info = NodeInfo {
parents: [key2.clone(), key1.clone()],
linknode: HgId::random(&mut rng),
};
nodes.insert(key3.clone(), info.clone());
nodes
}
#[test]
fn test_get_node_info() {
let mut rng = ChaChaRng::from_seed([0u8; 32]);
let tempdir = TempDir::new().unwrap();
let nodes = get_nodes(&mut rng);
let pack = make_historypack(&tempdir, &nodes);
for (ref key, ref info) in nodes.iter() {
let response: NodeInfo = pack.get_node_info(key).unwrap().unwrap();
assert_eq!(response, **info);
}
}
#[test]
fn test_get_missing() {
let mut rng = ChaChaRng::from_seed([0u8; 32]);
let tempdir = TempDir::new().unwrap();
let nodes = get_nodes(&mut rng);
let pack = make_historypack(&tempdir, &nodes);
let mut test_keys: Vec<StoreKey> = nodes.keys().map(|k| StoreKey::from(k)).collect();
let missing_key = key("missing", "f0f0f0");
test_keys.push(StoreKey::from(&missing_key));
let missing = pack.get_missing(&test_keys[..]).unwrap();
assert_eq!(vec![StoreKey::from(missing_key)], missing);
}
#[test]
fn test_iter() {
let mut rng = ChaChaRng::from_seed([0u8; 32]);
let tempdir = TempDir::new().unwrap();
let nodes = get_nodes(&mut rng);
let pack = make_historypack(&tempdir, &nodes);
let mut keys: Vec<Key> = nodes.keys().map(|k| k.clone()).collect();
keys.sort_unstable();
let mut iter_keys = pack
.to_keys()
.into_iter()
.collect::<Result<Vec<Key>>>()
.unwrap();
iter_keys.sort_unstable();
assert_eq!(iter_keys, keys,);
}
#[test]
fn test_open_v0() {
let mut rng = ChaChaRng::from_seed([0u8; 32]);
let tempdir = TempDir::new().unwrap();
let nodes = get_nodes(&mut rng);
let mutpack = MutableHistoryPack::new(tempdir.path(), HistoryPackVersion::One);
for (ref key, ref info) in nodes.iter() {
mutpack.add(key.clone(), info.clone()).unwrap();
}
let | HistoryPackIterator | identifier_name |
historypack.rs | copyfrom is the
//! filepath of the other file.
//!
//!.histidx
//! The index file provides a mapping from filename to the file section in
//! the histpack. In V1 it also contains sub-indexes for specific nodes
//! within each file. It consists of three parts, the fanout, the file index
//! and the hgid indexes.
//!
//! The file index is a list of index entries, sorted by filename hash (one
//! per file section in the pack). Each entry has:
//!
//! - hgid (The 20 byte hash of the filename)
//! - pack entry offset (The location of this file section in the histpack)
//! - pack content size (The on-disk length of this file section's pack
//! data)
//! - hgid index offset (The location of the file's hgid index in the index
//! file) [1]
//! - hgid index size (the on-disk length of this file's hgid index) [1]
//!
//! The fanout is a quick lookup table to reduce the number of steps for
//! bisecting the index. It is a series of 4 byte pointers to positions
//! within the index. It has 2^16 entries, which corresponds to hash
//! prefixes [00, 01, 02,..., FD, FE, FF]. Example: the pointer in slot 4F
//! points to the index position of the first revision whose hgid starts
//! with 4F. This saves log(2^16) bisect steps.
//!
//! dataidx = <fanouttable>
//! <file count: 8 byte unsigned> [1]
//! <fileindex>
//! <hgid count: 8 byte unsigned> [1]
//! [<nodeindex>,...] [1]
//! fanouttable = [<index offset: 4 byte unsigned int>,...] (2^16 entries)
//!
//! fileindex = [<file index entry>,...]
//! fileindexentry = <hgid: 20 byte>
//! <pack file section offset: 8 byte unsigned int>
//! <pack file section size: 8 byte unsigned int>
//! <hgid index offset: 4 byte unsigned int> [1]
//! <hgid index size: 4 byte unsigned int> [1]
//! nodeindex = [<hgid index entry>,...] [1]
//! filename = <filename len : 2 byte unsigned int><filename value> [1]
//! nodeindexentry = <hgid: 20 byte> [1]
//! <pack file hgid offset: 8 byte unsigned int> [1]
//!
//! ```
//! [1]: new in version 1.
use std::{
fs::File,
io::{Cursor, Read, Write},
mem::{drop, take},
path::{Path, PathBuf},
sync::Arc,
};
use anyhow::{format_err, Result};
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use memmap::{Mmap, MmapOptions};
use thiserror::Error;
use types::{HgId, Key, NodeInfo, RepoPath, RepoPathBuf};
use util::path::remove_file;
use crate::{
historyindex::HistoryIndex,
historystore::HgIdHistoryStore,
localstore::{ExtStoredPolicy, LocalStore, StoreFromPath},
repack::{Repackable, ToKeys},
sliceext::SliceExt,
types::StoreKey,
};
#[derive(Debug, Error)]
#[error("Historypack Error: {0:?}")]
struct HistoryPackError(String);
#[derive(Clone, Debug, PartialEq)]
pub enum HistoryPackVersion {
Zero,
One,
}
impl HistoryPackVersion {
fn new(value: u8) -> Result<Self> {
match value {
0 => Ok(HistoryPackVersion::Zero),
1 => Ok(HistoryPackVersion::One),
_ => Err(HistoryPackError(format!(
"invalid history pack version number '{:?}'",
value
))
.into()),
}
}
}
impl From<HistoryPackVersion> for u8 {
fn from(version: HistoryPackVersion) -> u8 {
match version {
HistoryPackVersion::Zero => 0,
HistoryPackVersion::One => 1,
}
}
}
#[derive(Debug, PartialEq)]
pub(crate) struct FileSectionHeader<'a> {
pub file_name: &'a RepoPath,
pub count: u32,
}
#[derive(Debug, PartialEq)]
pub struct HistoryEntry<'a> {
pub hgid: HgId,
pub p1: HgId,
pub p2: HgId,
pub link_hgid: HgId,
pub copy_from: Option<&'a RepoPath>,
}
fn read_slice<'a, 'b>(cur: &'a mut Cursor<&[u8]>, buf: &'b [u8], size: usize) -> Result<&'b [u8]> {
let start = cur.position() as usize;
let end = start + size;
let file_name = buf.get_err(start..end)?;
cur.set_position(end as u64);
Ok(file_name)
}
impl<'a> FileSectionHeader<'a> {
pub(crate) fn read(buf: &[u8]) -> Result<FileSectionHeader> {
let mut cur = Cursor::new(buf);
let file_name_len = cur.read_u16::<BigEndian>()? as usize;
let file_name_slice = read_slice(&mut cur, &buf, file_name_len)?;
let file_name = RepoPath::from_utf8(file_name_slice)?;
let count = cur.read_u32::<BigEndian>()?;
Ok(FileSectionHeader { file_name, count })
}
pub fn write<T: Write>(&self, writer: &mut T) -> Result<()> {
let file_name_slice = self.file_name.as_byte_slice();
writer.write_u16::<BigEndian>(file_name_slice.len() as u16)?;
writer.write_all(file_name_slice)?;
writer.write_u32::<BigEndian>(self.count)?;
Ok(())
}
}
impl<'a> HistoryEntry<'a> {
pub(crate) fn read(buf: &[u8]) -> Result<HistoryEntry> {
let mut cur = Cursor::new(buf);
let mut hgid_buf: [u8; 20] = Default::default();
// Node
cur.read_exact(&mut hgid_buf)?;
let hgid = HgId::from(&hgid_buf);
// Parents
cur.read_exact(&mut hgid_buf)?;
let p1 = HgId::from(&hgid_buf);
cur.read_exact(&mut hgid_buf)?;
let p2 = HgId::from(&hgid_buf);
// LinkNode
cur.read_exact(&mut hgid_buf)?;
let link_hgid = HgId::from(&hgid_buf);
// Copyfrom
let copy_from_len = cur.read_u16::<BigEndian>()? as usize;
let copy_from = if copy_from_len > 0 {
let slice = read_slice(&mut cur, &buf, copy_from_len)?;
Some(RepoPath::from_utf8(slice)?)
} else {
None
};
Ok(HistoryEntry {
hgid,
p1,
p2,
link_hgid,
copy_from,
})
}
pub fn write<T: Write>(
writer: &mut T,
hgid: &HgId,
p1: &HgId,
p2: &HgId,
linknode: &HgId,
copy_from: &Option<&RepoPath>,
) -> Result<()> {
writer.write_all(hgid.as_ref())?;
writer.write_all(p1.as_ref())?;
writer.write_all(p2.as_ref())?;
writer.write_all(linknode.as_ref())?;
match *copy_from {
Some(file_name) => {
let file_name_slice = file_name.as_byte_slice();
writer.write_u16::<BigEndian>(file_name_slice.len() as u16)?;
writer.write_all(file_name_slice)?;
}
None => writer.write_u16::<BigEndian>(0)?,
};
Ok(())
}
}
pub struct HistoryPack {
mmap: Mmap,
#[allow(dead_code)]
version: HistoryPackVersion,
index: HistoryIndex,
base_path: Arc<PathBuf>,
pack_path: PathBuf,
index_path: PathBuf,
}
impl HistoryPack {
pub fn new(path: impl AsRef<Path>) -> Result<Self> {
HistoryPack::with_path(path.as_ref())
}
fn with_path(path: &Path) -> Result<Self> {
let base_path = PathBuf::from(path);
let pack_path = path.with_extension("histpack");
let file = File::open(&pack_path)?;
let len = file.metadata()?.len();
if len < 1 {
return Err(format_err!(
"empty histpack '{:?}' is invalid",
path.to_str().unwrap_or("<unknown>")
));
}
let mmap = unsafe { MmapOptions::new().len(len as usize).map(&file)? };
let version = HistoryPackVersion::new(mmap[0])?;
if version!= HistoryPackVersion::One {
return Err(HistoryPackError(format!("version {:?} not supported", version)).into());
}
let index_path = path.with_extension("histidx");
Ok(HistoryPack {
mmap,
version,
index: HistoryIndex::new(&index_path)?,
base_path: Arc::new(base_path),
pack_path,
index_path,
})
}
pub fn len(&self) -> usize {
self.mmap.len()
}
pub fn base_path(&self) -> &Path {
&self.base_path
}
pub fn pack_path(&self) -> &Path {
&self.pack_path
}
pub fn index_path(&self) -> &Path {
&self.index_path
}
fn read_file_section_header(&self, offset: u64) -> Result<FileSectionHeader> {
FileSectionHeader::read(&self.mmap.as_ref().get_err(offset as usize..)?)
}
fn read_history_entry(&self, offset: u64) -> Result<HistoryEntry> {
HistoryEntry::read(&self.mmap.as_ref().get_err(offset as usize..)?)
}
fn read_node_info(&self, key: &Key, offset: u64) -> Result<NodeInfo> {
let entry = self.read_history_entry(offset)?;
assert_eq!(entry.hgid, key.hgid);
let p1 = Key::new(
match entry.copy_from {
Some(value) => value.to_owned(),
None => key.path.clone(),
},
entry.p1.clone(),
);
let p2 = Key::new(key.path.clone(), entry.p2.clone());
Ok(NodeInfo {
parents: [p1, p2],
linknode: entry.link_hgid.clone(),
})
}
}
impl HgIdHistoryStore for HistoryPack {
fn get_node_info(&self, key: &Key) -> Result<Option<NodeInfo>> {
let hgid_location = match self.index.get_hgid_entry(key)? {
None => return Ok(None),
Some(location) => location,
};
self.read_node_info(key, hgid_location.offset).map(Some)
}
fn refresh(&self) -> Result<()> {
Ok(())
}
}
impl StoreFromPath for HistoryPack {
fn from_path(path: &Path, _extstored_policy: ExtStoredPolicy) -> Result<Self> {
HistoryPack::new(path)
}
}
impl LocalStore for HistoryPack {
fn get_missing(&self, keys: &[StoreKey]) -> Result<Vec<StoreKey>> {
Ok(keys
.iter()
.filter(|k| match k {
StoreKey::HgId(k) => match self.index.get_hgid_entry(k) {
Ok(None) | Err(_) => true,
Ok(Some(_)) => false,
},
StoreKey::Content(_, _) => true,
})
.cloned()
.collect())
}
}
impl ToKeys for HistoryPack {
fn to_keys(&self) -> Vec<Result<Key>> {
HistoryPackIterator::new(self).collect()
}
}
impl Repackable for HistoryPack {
fn delete(mut self) -> Result<()> {
// On some platforms, removing a file can fail if it's still opened or mapped, let's make
// sure we close and unmap them before deletion.
let pack_path = take(&mut self.pack_path);
let index_path = take(&mut self.index_path);
drop(self);
let result1 = remove_file(&pack_path);
let result2 = remove_file(&index_path);
// Only check for errors after both have run. That way if pack_path doesn't exist,
// index_path is still deleted.
result1?;
result2?;
Ok(())
}
fn size(&self) -> u64 {
self.mmap.len() as u64
}
}
struct HistoryPackIterator<'a> {
pack: &'a HistoryPack,
offset: u64,
current_name: RepoPathBuf,
current_remaining: u32,
}
impl<'a> HistoryPackIterator<'a> {
pub fn new(pack: &'a HistoryPack) -> Self {
HistoryPackIterator {
pack,
offset: 1, // Start after the header byte
current_name: RepoPathBuf::new(),
current_remaining: 0,
}
}
}
impl<'a> Iterator for HistoryPackIterator<'a> {
type Item = Result<Key>;
fn next(&mut self) -> Option<Self::Item> {
while self.current_remaining == 0 && (self.offset as usize) < self.pack.len() {
let file_header = self.pack.read_file_section_header(self.offset);
match file_header {
Ok(header) => {
let file_name_slice = header.file_name.as_byte_slice();
self.current_name = header.file_name.to_owned();
self.current_remaining = header.count;
self.offset += 4 + 2 + file_name_slice.len() as u64;
}
Err(e) => {
self.offset = self.pack.len() as u64;
return Some(Err(e));
}
};
}
if self.offset as usize >= self.pack.len() {
return None;
}
let entry = self.pack.read_history_entry(self.offset);
self.current_remaining -= 1;
Some(match entry {
Ok(ref e) => {
self.offset += 80;
self.offset += match e.copy_from {
Some(path) => 2 + path.as_byte_slice().len() as u64,
None => 2,
};
Ok(Key::new(self.current_name.clone(), e.hgid))
}
Err(e) => {
// The entry is corrupted, and we have no way to know where the next one is
// located, let's forcibly stop the iteration.
self.offset = self.pack.len() as u64;
Err(e)
}
})
}
}
#[cfg(test)]
pub mod tests {
use super::*;
use quickcheck::quickcheck;
use rand::SeedableRng;
use rand_chacha::ChaChaRng;
use tempfile::TempDir;
use std::{
collections::HashMap,
fs::{set_permissions, File, OpenOptions},
};
use types::{testutil::*, RepoPathBuf};
use crate::{historystore::HgIdMutableHistoryStore, mutablehistorypack::MutableHistoryPack};
pub fn make_historypack(tempdir: &TempDir, nodes: &HashMap<Key, NodeInfo>) -> HistoryPack {
let mutpack = MutableHistoryPack::new(tempdir.path(), HistoryPackVersion::One);
for (ref key, ref info) in nodes.iter() {
mutpack.add(key.clone(), info.clone()).unwrap();
}
let path = &mutpack.flush().unwrap().unwrap()[0];
HistoryPack::new(&path).unwrap()
}
pub fn get_nodes(mut rng: &mut ChaChaRng) -> HashMap<Key, NodeInfo> {
let file1 = RepoPath::from_str("path").unwrap();
let file2 = RepoPath::from_str("path/file").unwrap();
let null = HgId::null_id();
let node1 = HgId::random(&mut rng);
let node2 = HgId::random(&mut rng);
let node3 = HgId::random(&mut rng);
let node4 = HgId::random(&mut rng);
let node5 = HgId::random(&mut rng);
let node6 = HgId::random(&mut rng);
let mut nodes = HashMap::new();
// Insert key 1
let key1 = Key::new(file1.to_owned(), node2.clone());
let info = NodeInfo {
parents: [
Key::new(file1.to_owned(), node1.clone()),
Key::new(file1.to_owned(), null.clone()),
],
linknode: HgId::random(&mut rng),
};
nodes.insert(key1.clone(), info.clone());
// Insert key 2
let key2 = Key::new(file2.to_owned(), node3.clone());
let info = NodeInfo {
parents: [
Key::new(file2.to_owned(), node5.clone()),
Key::new(file2.to_owned(), node6.clone()),
],
linknode: HgId::random(&mut rng),
};
nodes.insert(key2.clone(), info.clone());
// Insert key 3
let key3 = Key::new(file1.to_owned(), node4.clone());
let info = NodeInfo {
parents: [key2.clone(), key1.clone()],
linknode: HgId::random(&mut rng),
};
nodes.insert(key3.clone(), info.clone());
nodes
}
#[test]
fn test_get_node_info() {
let mut rng = ChaChaRng::from_seed([0u8; 32]);
let tempdir = TempDir::new().unwrap();
let nodes = get_nodes(&mut rng);
let pack = make_historypack(&tempdir, &nodes);
for (ref key, ref info) in nodes.iter() {
let response: NodeInfo = pack.get_node_info(key).unwrap().unwrap();
assert_eq!(response, **info);
}
}
#[test]
fn test_get_missing() {
let mut rng = ChaChaRng::from_seed([0u8; 32]);
let tempdir = TempDir::new().unwrap();
let nodes = get_nodes(&mut rng);
let pack = make_historypack(&tempdir, &nodes);
let mut test_keys: Vec<StoreKey> = nodes.keys().map(|k| StoreKey::from(k)).collect();
let missing_key = key("missing", "f0f0f0");
test_keys.push(StoreKey::from(&missing_key));
let missing = pack.get_missing(&test_keys[..]).unwrap();
assert_eq!(vec![StoreKey::from(missing_key)], missing);
}
#[test]
fn test_iter() {
let mut rng = ChaChaRng::from_seed([0u8; 32]);
let tempdir = TempDir::new().unwrap();
let nodes = get_nodes(&mut rng);
let pack = make_historypack(&tempdir, &nodes);
let mut keys: Vec<Key> = nodes.keys().map(|k| k.clone()).collect();
keys.sort_unstable();
let mut iter_keys = pack
.to_keys()
.into_iter()
.collect::<Result<Vec<Key>>>()
.unwrap();
iter_keys.sort_unstable();
assert_eq!(iter_keys, keys,);
}
#[test]
fn test_open_v0() {
let mut rng = ChaChaRng::from_seed([0u8; 32]);
let tempdir = TempDir::new().unwrap();
let nodes = get_nodes(&mut rng);
let mutpack = MutableHistoryPack::new(tempdir.path(), HistoryPackVersion::One);
for (ref key, ref info) in nodes.iter() {
mutpack.add(key.clone(), info.clone()).unwrap();
}
| let path = &mutpack.flush().unwrap().unwrap()[0];
let pack_path = path.with_extension("histpack"); | random_line_split |
|
historypack.rs | If a given entry has a parent from another file (a copy)
//! then p1node is the hgid from the other file, and copyfrom is the
//! filepath of the other file.
//!
//!.histidx
//! The index file provides a mapping from filename to the file section in
//! the histpack. In V1 it also contains sub-indexes for specific nodes
//! within each file. It consists of three parts, the fanout, the file index
//! and the hgid indexes.
//!
//! The file index is a list of index entries, sorted by filename hash (one
//! per file section in the pack). Each entry has:
//!
//! - hgid (The 20 byte hash of the filename)
//! - pack entry offset (The location of this file section in the histpack)
//! - pack content size (The on-disk length of this file section's pack
//! data)
//! - hgid index offset (The location of the file's hgid index in the index
//! file) [1]
//! - hgid index size (the on-disk length of this file's hgid index) [1]
//!
//! The fanout is a quick lookup table to reduce the number of steps for
//! bisecting the index. It is a series of 4 byte pointers to positions
//! within the index. It has 2^16 entries, which corresponds to hash
//! prefixes [00, 01, 02,..., FD, FE, FF]. Example: the pointer in slot 4F
//! points to the index position of the first revision whose hgid starts
//! with 4F. This saves log(2^16) bisect steps.
//!
//! dataidx = <fanouttable>
//! <file count: 8 byte unsigned> [1]
//! <fileindex>
//! <hgid count: 8 byte unsigned> [1]
//! [<nodeindex>,...] [1]
//! fanouttable = [<index offset: 4 byte unsigned int>,...] (2^16 entries)
//!
//! fileindex = [<file index entry>,...]
//! fileindexentry = <hgid: 20 byte>
//! <pack file section offset: 8 byte unsigned int>
//! <pack file section size: 8 byte unsigned int>
//! <hgid index offset: 4 byte unsigned int> [1]
//! <hgid index size: 4 byte unsigned int> [1]
//! nodeindex = [<hgid index entry>,...] [1]
//! filename = <filename len : 2 byte unsigned int><filename value> [1]
//! nodeindexentry = <hgid: 20 byte> [1]
//! <pack file hgid offset: 8 byte unsigned int> [1]
//!
//! ```
//! [1]: new in version 1.
use std::{
fs::File,
io::{Cursor, Read, Write},
mem::{drop, take},
path::{Path, PathBuf},
sync::Arc,
};
use anyhow::{format_err, Result};
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use memmap::{Mmap, MmapOptions};
use thiserror::Error;
use types::{HgId, Key, NodeInfo, RepoPath, RepoPathBuf};
use util::path::remove_file;
use crate::{
historyindex::HistoryIndex,
historystore::HgIdHistoryStore,
localstore::{ExtStoredPolicy, LocalStore, StoreFromPath},
repack::{Repackable, ToKeys},
sliceext::SliceExt,
types::StoreKey,
};
#[derive(Debug, Error)]
#[error("Historypack Error: {0:?}")]
struct HistoryPackError(String);
#[derive(Clone, Debug, PartialEq)]
pub enum HistoryPackVersion {
Zero,
One,
}
impl HistoryPackVersion {
fn new(value: u8) -> Result<Self> {
match value {
0 => Ok(HistoryPackVersion::Zero),
1 => Ok(HistoryPackVersion::One),
_ => Err(HistoryPackError(format!(
"invalid history pack version number '{:?}'",
value
))
.into()),
}
}
}
impl From<HistoryPackVersion> for u8 {
fn from(version: HistoryPackVersion) -> u8 {
match version {
HistoryPackVersion::Zero => 0,
HistoryPackVersion::One => 1,
}
}
}
#[derive(Debug, PartialEq)]
pub(crate) struct FileSectionHeader<'a> {
pub file_name: &'a RepoPath,
pub count: u32,
}
#[derive(Debug, PartialEq)]
pub struct HistoryEntry<'a> {
pub hgid: HgId,
pub p1: HgId,
pub p2: HgId,
pub link_hgid: HgId,
pub copy_from: Option<&'a RepoPath>,
}
fn read_slice<'a, 'b>(cur: &'a mut Cursor<&[u8]>, buf: &'b [u8], size: usize) -> Result<&'b [u8]> {
let start = cur.position() as usize;
let end = start + size;
let file_name = buf.get_err(start..end)?;
cur.set_position(end as u64);
Ok(file_name)
}
impl<'a> FileSectionHeader<'a> {
pub(crate) fn read(buf: &[u8]) -> Result<FileSectionHeader> {
let mut cur = Cursor::new(buf);
let file_name_len = cur.read_u16::<BigEndian>()? as usize;
let file_name_slice = read_slice(&mut cur, &buf, file_name_len)?;
let file_name = RepoPath::from_utf8(file_name_slice)?;
let count = cur.read_u32::<BigEndian>()?;
Ok(FileSectionHeader { file_name, count })
}
pub fn write<T: Write>(&self, writer: &mut T) -> Result<()> {
let file_name_slice = self.file_name.as_byte_slice();
writer.write_u16::<BigEndian>(file_name_slice.len() as u16)?;
writer.write_all(file_name_slice)?;
writer.write_u32::<BigEndian>(self.count)?;
Ok(())
}
}
impl<'a> HistoryEntry<'a> {
pub(crate) fn read(buf: &[u8]) -> Result<HistoryEntry> {
let mut cur = Cursor::new(buf);
let mut hgid_buf: [u8; 20] = Default::default();
// Node
cur.read_exact(&mut hgid_buf)?;
let hgid = HgId::from(&hgid_buf);
// Parents
cur.read_exact(&mut hgid_buf)?;
let p1 = HgId::from(&hgid_buf);
cur.read_exact(&mut hgid_buf)?;
let p2 = HgId::from(&hgid_buf);
// LinkNode
cur.read_exact(&mut hgid_buf)?;
let link_hgid = HgId::from(&hgid_buf);
// Copyfrom
let copy_from_len = cur.read_u16::<BigEndian>()? as usize;
let copy_from = if copy_from_len > 0 {
let slice = read_slice(&mut cur, &buf, copy_from_len)?;
Some(RepoPath::from_utf8(slice)?)
} else {
None
};
Ok(HistoryEntry {
hgid,
p1,
p2,
link_hgid,
copy_from,
})
}
pub fn write<T: Write>(
writer: &mut T,
hgid: &HgId,
p1: &HgId,
p2: &HgId,
linknode: &HgId,
copy_from: &Option<&RepoPath>,
) -> Result<()> {
writer.write_all(hgid.as_ref())?;
writer.write_all(p1.as_ref())?;
writer.write_all(p2.as_ref())?;
writer.write_all(linknode.as_ref())?;
match *copy_from {
Some(file_name) => {
let file_name_slice = file_name.as_byte_slice();
writer.write_u16::<BigEndian>(file_name_slice.len() as u16)?;
writer.write_all(file_name_slice)?;
}
None => writer.write_u16::<BigEndian>(0)?,
};
Ok(())
}
}
pub struct HistoryPack {
mmap: Mmap,
#[allow(dead_code)]
version: HistoryPackVersion,
index: HistoryIndex,
base_path: Arc<PathBuf>,
pack_path: PathBuf,
index_path: PathBuf,
}
impl HistoryPack {
pub fn new(path: impl AsRef<Path>) -> Result<Self> {
HistoryPack::with_path(path.as_ref())
}
fn with_path(path: &Path) -> Result<Self> | mmap,
version,
index: HistoryIndex::new(&index_path)?,
base_path: Arc::new(base_path),
pack_path,
index_path,
})
}
pub fn len(&self) -> usize {
self.mmap.len()
}
pub fn base_path(&self) -> &Path {
&self.base_path
}
pub fn pack_path(&self) -> &Path {
&self.pack_path
}
pub fn index_path(&self) -> &Path {
&self.index_path
}
fn read_file_section_header(&self, offset: u64) -> Result<FileSectionHeader> {
FileSectionHeader::read(&self.mmap.as_ref().get_err(offset as usize..)?)
}
fn read_history_entry(&self, offset: u64) -> Result<HistoryEntry> {
HistoryEntry::read(&self.mmap.as_ref().get_err(offset as usize..)?)
}
fn read_node_info(&self, key: &Key, offset: u64) -> Result<NodeInfo> {
let entry = self.read_history_entry(offset)?;
assert_eq!(entry.hgid, key.hgid);
let p1 = Key::new(
match entry.copy_from {
Some(value) => value.to_owned(),
None => key.path.clone(),
},
entry.p1.clone(),
);
let p2 = Key::new(key.path.clone(), entry.p2.clone());
Ok(NodeInfo {
parents: [p1, p2],
linknode: entry.link_hgid.clone(),
})
}
}
impl HgIdHistoryStore for HistoryPack {
fn get_node_info(&self, key: &Key) -> Result<Option<NodeInfo>> {
let hgid_location = match self.index.get_hgid_entry(key)? {
None => return Ok(None),
Some(location) => location,
};
self.read_node_info(key, hgid_location.offset).map(Some)
}
fn refresh(&self) -> Result<()> {
Ok(())
}
}
impl StoreFromPath for HistoryPack {
fn from_path(path: &Path, _extstored_policy: ExtStoredPolicy) -> Result<Self> {
HistoryPack::new(path)
}
}
impl LocalStore for HistoryPack {
fn get_missing(&self, keys: &[StoreKey]) -> Result<Vec<StoreKey>> {
Ok(keys
.iter()
.filter(|k| match k {
StoreKey::HgId(k) => match self.index.get_hgid_entry(k) {
Ok(None) | Err(_) => true,
Ok(Some(_)) => false,
},
StoreKey::Content(_, _) => true,
})
.cloned()
.collect())
}
}
impl ToKeys for HistoryPack {
fn to_keys(&self) -> Vec<Result<Key>> {
HistoryPackIterator::new(self).collect()
}
}
impl Repackable for HistoryPack {
fn delete(mut self) -> Result<()> {
// On some platforms, removing a file can fail if it's still opened or mapped, let's make
// sure we close and unmap them before deletion.
let pack_path = take(&mut self.pack_path);
let index_path = take(&mut self.index_path);
drop(self);
let result1 = remove_file(&pack_path);
let result2 = remove_file(&index_path);
// Only check for errors after both have run. That way if pack_path doesn't exist,
// index_path is still deleted.
result1?;
result2?;
Ok(())
}
fn size(&self) -> u64 {
self.mmap.len() as u64
}
}
struct HistoryPackIterator<'a> {
pack: &'a HistoryPack,
offset: u64,
current_name: RepoPathBuf,
current_remaining: u32,
}
impl<'a> HistoryPackIterator<'a> {
pub fn new(pack: &'a HistoryPack) -> Self {
HistoryPackIterator {
pack,
offset: 1, // Start after the header byte
current_name: RepoPathBuf::new(),
current_remaining: 0,
}
}
}
impl<'a> Iterator for HistoryPackIterator<'a> {
type Item = Result<Key>;
fn next(&mut self) -> Option<Self::Item> {
while self.current_remaining == 0 && (self.offset as usize) < self.pack.len() {
let file_header = self.pack.read_file_section_header(self.offset);
match file_header {
Ok(header) => {
let file_name_slice = header.file_name.as_byte_slice();
self.current_name = header.file_name.to_owned();
self.current_remaining = header.count;
self.offset += 4 + 2 + file_name_slice.len() as u64;
}
Err(e) => {
self.offset = self.pack.len() as u64;
return Some(Err(e));
}
};
}
if self.offset as usize >= self.pack.len() {
return None;
}
let entry = self.pack.read_history_entry(self.offset);
self.current_remaining -= 1;
Some(match entry {
Ok(ref e) => {
self.offset += 80;
self.offset += match e.copy_from {
Some(path) => 2 + path.as_byte_slice().len() as u64,
None => 2,
};
Ok(Key::new(self.current_name.clone(), e.hgid))
}
Err(e) => {
// The entry is corrupted, and we have no way to know where the next one is
// located, let's forcibly stop the iteration.
self.offset = self.pack.len() as u64;
Err(e)
}
})
}
}
#[cfg(test)]
pub mod tests {
use super::*;
use quickcheck::quickcheck;
use rand::SeedableRng;
use rand_chacha::ChaChaRng;
use tempfile::TempDir;
use std::{
collections::HashMap,
fs::{set_permissions, File, OpenOptions},
};
use types::{testutil::*, RepoPathBuf};
use crate::{historystore::HgIdMutableHistoryStore, mutablehistorypack::MutableHistoryPack};
pub fn make_historypack(tempdir: &TempDir, nodes: &HashMap<Key, NodeInfo>) -> HistoryPack {
let mutpack = MutableHistoryPack::new(tempdir.path(), HistoryPackVersion::One);
for (ref key, ref info) in nodes.iter() {
mutpack.add(key.clone(), info.clone()).unwrap();
}
let path = &mutpack.flush().unwrap().unwrap()[0];
HistoryPack::new(&path).unwrap()
}
pub fn get_nodes(mut rng: &mut ChaChaRng) -> HashMap<Key, NodeInfo> {
let file1 = RepoPath::from_str("path").unwrap();
let file2 = RepoPath::from_str("path/file").unwrap();
let null = HgId::null_id();
let node1 = HgId::random(&mut rng);
let node2 = HgId::random(&mut rng);
let node3 = HgId::random(&mut rng);
let node4 = HgId::random(&mut rng);
let node5 = HgId::random(&mut rng);
let node6 = HgId::random(&mut rng);
let mut nodes = HashMap::new();
// Insert key 1
let key1 = Key::new(file1.to_owned(), node2.clone());
let info = NodeInfo {
parents: [
Key::new(file1.to_owned(), node1.clone()),
Key::new(file1.to_owned(), null.clone()),
],
linknode: HgId::random(&mut rng),
};
nodes.insert(key1.clone(), info.clone());
// Insert key 2
let key2 = Key::new(file2.to_owned(), node3.clone());
let info = NodeInfo {
parents: [
Key::new(file2.to_owned(), node5.clone()),
Key::new(file2.to_owned(), node6.clone()),
],
linknode: HgId::random(&mut rng),
};
nodes.insert(key2.clone(), info.clone());
// Insert key 3
let key3 = Key::new(file1.to_owned(), node4.clone());
let info = NodeInfo {
parents: [key2.clone(), key1.clone()],
linknode: HgId::random(&mut rng),
};
nodes.insert(key3.clone(), info.clone());
nodes
}
#[test]
fn test_get_node_info() {
let mut rng = ChaChaRng::from_seed([0u8; 32]);
let tempdir = TempDir::new().unwrap();
let nodes = get_nodes(&mut rng);
let pack = make_historypack(&tempdir, &nodes);
for (ref key, ref info) in nodes.iter() {
let response: NodeInfo = pack.get_node_info(key).unwrap().unwrap();
assert_eq!(response, **info);
}
}
#[test]
fn test_get_missing() {
let mut rng = ChaChaRng::from_seed([0u8; 32]);
let tempdir = TempDir::new().unwrap();
let nodes = get_nodes(&mut rng);
let pack = make_historypack(&tempdir, &nodes);
let mut test_keys: Vec<StoreKey> = nodes.keys().map(|k| StoreKey::from(k)).collect();
let missing_key = key("missing", "f0f0f0");
test_keys.push(StoreKey::from(&missing_key));
let missing = pack.get_missing(&test_keys[..]).unwrap();
assert_eq!(vec![StoreKey::from(missing_key)], missing);
}
#[test]
fn test_iter() {
let mut rng = ChaChaRng::from_seed([0u8; 32]);
let tempdir = TempDir::new().unwrap();
let nodes = get_nodes(&mut rng);
let pack = make_historypack(&tempdir, &nodes);
let mut keys: Vec<Key> = nodes.keys().map(|k| k.clone()).collect();
keys.sort_unstable();
let mut iter_keys = pack
.to_keys()
.into_iter()
.collect::<Result<Vec<Key>>>()
.unwrap();
iter_keys.sort_unstable();
assert_eq!(iter_keys, keys,);
}
#[test]
fn test_open_v0() {
let mut rng = ChaChaRng::from_seed([0u8; 32]);
let tempdir = TempDir::new().unwrap();
let nodes = get_nodes(&mut rng);
let mutpack = MutableHistoryPack::new(tempdir.path(), HistoryPackVersion::One);
for (ref key, ref info) in nodes.iter() {
mutpack.add(key.clone(), info.clone()).unwrap();
}
let | {
let base_path = PathBuf::from(path);
let pack_path = path.with_extension("histpack");
let file = File::open(&pack_path)?;
let len = file.metadata()?.len();
if len < 1 {
return Err(format_err!(
"empty histpack '{:?}' is invalid",
path.to_str().unwrap_or("<unknown>")
));
}
let mmap = unsafe { MmapOptions::new().len(len as usize).map(&file)? };
let version = HistoryPackVersion::new(mmap[0])?;
if version != HistoryPackVersion::One {
return Err(HistoryPackError(format!("version {:?} not supported", version)).into());
}
let index_path = path.with_extension("histidx");
Ok(HistoryPack { | identifier_body |
webglprogram.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/. */
// https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl
use dom::bindings::codegen::Bindings::WebGLProgramBinding;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{JS, MutNullableHeap, Root};
use dom::bindings::utils::reflect_dom_object;
use dom::webglobject::WebGLObject;
use dom::webglshader::{WebGLShader, WebGLShaderHelpers};
use dom::webglrenderingcontext::MAX_UNIFORM_AND_ATTRIBUTE_LEN;
use dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLRenderingContextConstants as constants;
use canvas_traits::{CanvasMsg, CanvasWebGLMsg, WebGLResult, WebGLError};
use std::sync::mpsc::{channel, Sender};
use std::cell::Cell;
#[dom_struct]
pub struct WebGLProgram {
webgl_object: WebGLObject,
id: u32,
is_deleted: Cell<bool>,
fragment_shader: MutNullableHeap<JS<WebGLShader>>,
vertex_shader: MutNullableHeap<JS<WebGLShader>>,
renderer: Sender<CanvasMsg>,
}
impl WebGLProgram {
fn new_inherited(renderer: Sender<CanvasMsg>, id: u32) -> WebGLProgram {
WebGLProgram {
webgl_object: WebGLObject::new_inherited(),
id: id,
is_deleted: Cell::new(false),
fragment_shader: Default::default(),
vertex_shader: Default::default(),
renderer: renderer,
}
}
pub fn maybe_new(global: GlobalRef, renderer: Sender<CanvasMsg>) -> Option<Root<WebGLProgram>> {
let (sender, receiver) = channel();
renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::CreateProgram(sender))).unwrap();
let result = receiver.recv().unwrap();
result.map(|program_id| WebGLProgram::new(global, renderer, *program_id))
}
pub fn new(global: GlobalRef, renderer: Sender<CanvasMsg>, id: u32) -> Root<WebGLProgram> {
reflect_dom_object(box WebGLProgram::new_inherited(renderer, id), global, WebGLProgramBinding::Wrap)
}
}
pub trait WebGLProgramHelpers {
fn delete(self);
fn link(self);
fn use_program(self);
fn attach_shader(self, shader: &WebGLShader) -> WebGLResult<()>;
fn get_attrib_location(self, name: String) -> WebGLResult<Option<i32>>;
fn get_uniform_location(self, name: String) -> WebGLResult<Option<i32>>;
}
impl<'a> WebGLProgramHelpers for &'a WebGLProgram {
/// glDeleteProgram
fn | (self) {
if!self.is_deleted.get() {
self.is_deleted.set(true);
self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::DeleteProgram(self.id))).unwrap();
}
}
/// glLinkProgram
fn link(self) {
self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::LinkProgram(self.id))).unwrap();
}
/// glUseProgram
fn use_program(self) {
self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::UseProgram(self.id))).unwrap();
}
/// glAttachShader
fn attach_shader(self, shader: &WebGLShader) -> WebGLResult<()> {
let shader_slot = match shader.gl_type() {
constants::FRAGMENT_SHADER => &self.fragment_shader,
constants::VERTEX_SHADER => &self.vertex_shader,
_ => return Err(WebGLError::InvalidOperation),
};
// TODO(ecoal95): Differentiate between same shader already assigned and other previous
// shader.
if shader_slot.get().is_some() {
return Err(WebGLError::InvalidOperation);
}
shader_slot.set(Some(JS::from_ref(shader)));
self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::AttachShader(self.id, shader.id()))).unwrap();
Ok(())
}
/// glGetAttribLocation
fn get_attrib_location(self, name: String) -> WebGLResult<Option<i32>> {
if name.len() > MAX_UNIFORM_AND_ATTRIBUTE_LEN {
return Err(WebGLError::InvalidValue);
}
// Check if the name is reserved
if name.starts_with("webgl") || name.starts_with("_webgl_") {
return Ok(None);
}
let (sender, receiver) = channel();
self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::GetAttribLocation(self.id, name, sender))).unwrap();
Ok(receiver.recv().unwrap())
}
/// glGetUniformLocation
fn get_uniform_location(self, name: String) -> WebGLResult<Option<i32>> {
if name.len() > MAX_UNIFORM_AND_ATTRIBUTE_LEN {
return Err(WebGLError::InvalidValue);
}
// Check if the name is reserved
if name.starts_with("webgl") || name.starts_with("_webgl_") {
return Ok(None);
}
let (sender, receiver) = channel();
self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::GetUniformLocation(self.id, name, sender))).unwrap();
Ok(receiver.recv().unwrap())
}
}
| delete | identifier_name |
webglprogram.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/. */
// https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl
use dom::bindings::codegen::Bindings::WebGLProgramBinding;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{JS, MutNullableHeap, Root};
use dom::bindings::utils::reflect_dom_object;
use dom::webglobject::WebGLObject;
use dom::webglshader::{WebGLShader, WebGLShaderHelpers};
use dom::webglrenderingcontext::MAX_UNIFORM_AND_ATTRIBUTE_LEN;
use dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLRenderingContextConstants as constants;
use canvas_traits::{CanvasMsg, CanvasWebGLMsg, WebGLResult, WebGLError};
use std::sync::mpsc::{channel, Sender};
use std::cell::Cell;
#[dom_struct]
pub struct WebGLProgram {
webgl_object: WebGLObject,
id: u32,
is_deleted: Cell<bool>,
fragment_shader: MutNullableHeap<JS<WebGLShader>>,
vertex_shader: MutNullableHeap<JS<WebGLShader>>,
renderer: Sender<CanvasMsg>,
}
impl WebGLProgram {
fn new_inherited(renderer: Sender<CanvasMsg>, id: u32) -> WebGLProgram {
WebGLProgram {
webgl_object: WebGLObject::new_inherited(),
id: id,
is_deleted: Cell::new(false),
fragment_shader: Default::default(),
vertex_shader: Default::default(),
renderer: renderer,
}
}
pub fn maybe_new(global: GlobalRef, renderer: Sender<CanvasMsg>) -> Option<Root<WebGLProgram>> {
let (sender, receiver) = channel();
renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::CreateProgram(sender))).unwrap();
let result = receiver.recv().unwrap();
result.map(|program_id| WebGLProgram::new(global, renderer, *program_id))
}
pub fn new(global: GlobalRef, renderer: Sender<CanvasMsg>, id: u32) -> Root<WebGLProgram> {
reflect_dom_object(box WebGLProgram::new_inherited(renderer, id), global, WebGLProgramBinding::Wrap)
}
}
pub trait WebGLProgramHelpers {
fn delete(self);
fn link(self);
fn use_program(self);
fn attach_shader(self, shader: &WebGLShader) -> WebGLResult<()>;
fn get_attrib_location(self, name: String) -> WebGLResult<Option<i32>>;
fn get_uniform_location(self, name: String) -> WebGLResult<Option<i32>>;
}
impl<'a> WebGLProgramHelpers for &'a WebGLProgram {
/// glDeleteProgram
fn delete(self) {
if!self.is_deleted.get() {
self.is_deleted.set(true);
self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::DeleteProgram(self.id))).unwrap();
}
}
/// glLinkProgram
fn link(self) {
self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::LinkProgram(self.id))).unwrap();
}
/// glUseProgram
fn use_program(self) {
self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::UseProgram(self.id))).unwrap();
}
/// glAttachShader
fn attach_shader(self, shader: &WebGLShader) -> WebGLResult<()> {
let shader_slot = match shader.gl_type() {
constants::FRAGMENT_SHADER => &self.fragment_shader,
constants::VERTEX_SHADER => &self.vertex_shader,
_ => return Err(WebGLError::InvalidOperation),
};
// TODO(ecoal95): Differentiate between same shader already assigned and other previous
// shader.
if shader_slot.get().is_some() {
return Err(WebGLError::InvalidOperation);
}
shader_slot.set(Some(JS::from_ref(shader)));
self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::AttachShader(self.id, shader.id()))).unwrap();
Ok(())
}
/// glGetAttribLocation
fn get_attrib_location(self, name: String) -> WebGLResult<Option<i32>> {
if name.len() > MAX_UNIFORM_AND_ATTRIBUTE_LEN {
return Err(WebGLError::InvalidValue);
}
// Check if the name is reserved
if name.starts_with("webgl") || name.starts_with("_webgl_") |
let (sender, receiver) = channel();
self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::GetAttribLocation(self.id, name, sender))).unwrap();
Ok(receiver.recv().unwrap())
}
/// glGetUniformLocation
fn get_uniform_location(self, name: String) -> WebGLResult<Option<i32>> {
if name.len() > MAX_UNIFORM_AND_ATTRIBUTE_LEN {
return Err(WebGLError::InvalidValue);
}
// Check if the name is reserved
if name.starts_with("webgl") || name.starts_with("_webgl_") {
return Ok(None);
}
let (sender, receiver) = channel();
self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::GetUniformLocation(self.id, name, sender))).unwrap();
Ok(receiver.recv().unwrap())
}
}
| {
return Ok(None);
} | conditional_block |
webglprogram.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/. */
// https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl
use dom::bindings::codegen::Bindings::WebGLProgramBinding;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{JS, MutNullableHeap, Root};
use dom::bindings::utils::reflect_dom_object;
use dom::webglobject::WebGLObject;
use dom::webglshader::{WebGLShader, WebGLShaderHelpers};
use dom::webglrenderingcontext::MAX_UNIFORM_AND_ATTRIBUTE_LEN;
use dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLRenderingContextConstants as constants;
use canvas_traits::{CanvasMsg, CanvasWebGLMsg, WebGLResult, WebGLError};
use std::sync::mpsc::{channel, Sender};
use std::cell::Cell;
#[dom_struct]
pub struct WebGLProgram {
webgl_object: WebGLObject,
id: u32,
is_deleted: Cell<bool>,
fragment_shader: MutNullableHeap<JS<WebGLShader>>,
vertex_shader: MutNullableHeap<JS<WebGLShader>>,
renderer: Sender<CanvasMsg>,
}
impl WebGLProgram {
fn new_inherited(renderer: Sender<CanvasMsg>, id: u32) -> WebGLProgram {
WebGLProgram {
webgl_object: WebGLObject::new_inherited(),
id: id,
is_deleted: Cell::new(false),
fragment_shader: Default::default(),
vertex_shader: Default::default(),
renderer: renderer,
}
}
pub fn maybe_new(global: GlobalRef, renderer: Sender<CanvasMsg>) -> Option<Root<WebGLProgram>> {
let (sender, receiver) = channel();
renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::CreateProgram(sender))).unwrap();
let result = receiver.recv().unwrap();
result.map(|program_id| WebGLProgram::new(global, renderer, *program_id))
}
pub fn new(global: GlobalRef, renderer: Sender<CanvasMsg>, id: u32) -> Root<WebGLProgram> {
reflect_dom_object(box WebGLProgram::new_inherited(renderer, id), global, WebGLProgramBinding::Wrap)
}
}
pub trait WebGLProgramHelpers {
fn delete(self);
fn link(self);
fn use_program(self);
fn attach_shader(self, shader: &WebGLShader) -> WebGLResult<()>;
fn get_attrib_location(self, name: String) -> WebGLResult<Option<i32>>;
fn get_uniform_location(self, name: String) -> WebGLResult<Option<i32>>;
}
impl<'a> WebGLProgramHelpers for &'a WebGLProgram {
/// glDeleteProgram
fn delete(self) {
if!self.is_deleted.get() {
self.is_deleted.set(true);
self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::DeleteProgram(self.id))).unwrap();
}
}
/// glLinkProgram
fn link(self) |
/// glUseProgram
fn use_program(self) {
self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::UseProgram(self.id))).unwrap();
}
/// glAttachShader
fn attach_shader(self, shader: &WebGLShader) -> WebGLResult<()> {
let shader_slot = match shader.gl_type() {
constants::FRAGMENT_SHADER => &self.fragment_shader,
constants::VERTEX_SHADER => &self.vertex_shader,
_ => return Err(WebGLError::InvalidOperation),
};
// TODO(ecoal95): Differentiate between same shader already assigned and other previous
// shader.
if shader_slot.get().is_some() {
return Err(WebGLError::InvalidOperation);
}
shader_slot.set(Some(JS::from_ref(shader)));
self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::AttachShader(self.id, shader.id()))).unwrap();
Ok(())
}
/// glGetAttribLocation
fn get_attrib_location(self, name: String) -> WebGLResult<Option<i32>> {
if name.len() > MAX_UNIFORM_AND_ATTRIBUTE_LEN {
return Err(WebGLError::InvalidValue);
}
// Check if the name is reserved
if name.starts_with("webgl") || name.starts_with("_webgl_") {
return Ok(None);
}
let (sender, receiver) = channel();
self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::GetAttribLocation(self.id, name, sender))).unwrap();
Ok(receiver.recv().unwrap())
}
/// glGetUniformLocation
fn get_uniform_location(self, name: String) -> WebGLResult<Option<i32>> {
if name.len() > MAX_UNIFORM_AND_ATTRIBUTE_LEN {
return Err(WebGLError::InvalidValue);
}
// Check if the name is reserved
if name.starts_with("webgl") || name.starts_with("_webgl_") {
return Ok(None);
}
let (sender, receiver) = channel();
self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::GetUniformLocation(self.id, name, sender))).unwrap();
Ok(receiver.recv().unwrap())
}
}
| {
self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::LinkProgram(self.id))).unwrap();
} | identifier_body |
webglprogram.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/. */
// https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl
use dom::bindings::codegen::Bindings::WebGLProgramBinding;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{JS, MutNullableHeap, Root};
use dom::bindings::utils::reflect_dom_object;
use dom::webglobject::WebGLObject;
use dom::webglshader::{WebGLShader, WebGLShaderHelpers};
use dom::webglrenderingcontext::MAX_UNIFORM_AND_ATTRIBUTE_LEN;
use dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLRenderingContextConstants as constants;
use canvas_traits::{CanvasMsg, CanvasWebGLMsg, WebGLResult, WebGLError};
use std::sync::mpsc::{channel, Sender};
use std::cell::Cell;
#[dom_struct]
pub struct WebGLProgram {
webgl_object: WebGLObject,
id: u32,
is_deleted: Cell<bool>,
fragment_shader: MutNullableHeap<JS<WebGLShader>>,
vertex_shader: MutNullableHeap<JS<WebGLShader>>,
renderer: Sender<CanvasMsg>,
}
impl WebGLProgram {
fn new_inherited(renderer: Sender<CanvasMsg>, id: u32) -> WebGLProgram {
WebGLProgram {
webgl_object: WebGLObject::new_inherited(),
id: id,
is_deleted: Cell::new(false),
fragment_shader: Default::default(),
vertex_shader: Default::default(),
renderer: renderer,
}
}
pub fn maybe_new(global: GlobalRef, renderer: Sender<CanvasMsg>) -> Option<Root<WebGLProgram>> {
let (sender, receiver) = channel();
renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::CreateProgram(sender))).unwrap();
let result = receiver.recv().unwrap();
result.map(|program_id| WebGLProgram::new(global, renderer, *program_id))
}
pub fn new(global: GlobalRef, renderer: Sender<CanvasMsg>, id: u32) -> Root<WebGLProgram> {
reflect_dom_object(box WebGLProgram::new_inherited(renderer, id), global, WebGLProgramBinding::Wrap)
}
}
pub trait WebGLProgramHelpers {
fn delete(self);
fn link(self);
fn use_program(self);
fn attach_shader(self, shader: &WebGLShader) -> WebGLResult<()>;
fn get_attrib_location(self, name: String) -> WebGLResult<Option<i32>>; | /// glDeleteProgram
fn delete(self) {
if!self.is_deleted.get() {
self.is_deleted.set(true);
self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::DeleteProgram(self.id))).unwrap();
}
}
/// glLinkProgram
fn link(self) {
self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::LinkProgram(self.id))).unwrap();
}
/// glUseProgram
fn use_program(self) {
self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::UseProgram(self.id))).unwrap();
}
/// glAttachShader
fn attach_shader(self, shader: &WebGLShader) -> WebGLResult<()> {
let shader_slot = match shader.gl_type() {
constants::FRAGMENT_SHADER => &self.fragment_shader,
constants::VERTEX_SHADER => &self.vertex_shader,
_ => return Err(WebGLError::InvalidOperation),
};
// TODO(ecoal95): Differentiate between same shader already assigned and other previous
// shader.
if shader_slot.get().is_some() {
return Err(WebGLError::InvalidOperation);
}
shader_slot.set(Some(JS::from_ref(shader)));
self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::AttachShader(self.id, shader.id()))).unwrap();
Ok(())
}
/// glGetAttribLocation
fn get_attrib_location(self, name: String) -> WebGLResult<Option<i32>> {
if name.len() > MAX_UNIFORM_AND_ATTRIBUTE_LEN {
return Err(WebGLError::InvalidValue);
}
// Check if the name is reserved
if name.starts_with("webgl") || name.starts_with("_webgl_") {
return Ok(None);
}
let (sender, receiver) = channel();
self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::GetAttribLocation(self.id, name, sender))).unwrap();
Ok(receiver.recv().unwrap())
}
/// glGetUniformLocation
fn get_uniform_location(self, name: String) -> WebGLResult<Option<i32>> {
if name.len() > MAX_UNIFORM_AND_ATTRIBUTE_LEN {
return Err(WebGLError::InvalidValue);
}
// Check if the name is reserved
if name.starts_with("webgl") || name.starts_with("_webgl_") {
return Ok(None);
}
let (sender, receiver) = channel();
self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::GetUniformLocation(self.id, name, sender))).unwrap();
Ok(receiver.recv().unwrap())
}
} | fn get_uniform_location(self, name: String) -> WebGLResult<Option<i32>>;
}
impl<'a> WebGLProgramHelpers for &'a WebGLProgram { | random_line_split |
hash.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity 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 General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Lenient hash json deserialization for test json files.
use std::str::FromStr;
use serde::{Deserialize, Deserializer, Serialize, Serializer, Error};
use serde::de::Visitor;
use rustc_serialize::hex::ToHex;
use util::hash::{H64 as Hash64, H160 as Hash160, H256 as Hash256, H520 as Hash520, H2048 as Hash2048};
macro_rules! impl_hash {
($name: ident, $inner: ident) => {
/// Lenient hash json deserialization for test json files.
#[derive(Default, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Clone)]
pub struct $name(pub $inner);
impl Into<$inner> for $name {
fn into(self) -> $inner {
self.0
}
}
impl From<$inner> for $name {
fn from(i: $inner) -> Self {
$name(i)
}
}
impl Deserialize for $name {
fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
where D: Deserializer {
struct HashVisitor;
impl Visitor for HashVisitor {
type Value = $name;
fn visit_str<E>(&mut self, value: &str) -> Result<Self::Value, E> where E: Error {
let value = match value.len() {
0 => $inner::from(0),
2 if value == "0x" => $inner::from(0),
_ if value.starts_with("0x") => $inner::from_str(&value[2..]).map_err(|_| {
Error::custom(format!("Invalid hex value {}.", value).as_str())
})?,
_ => $inner::from_str(value).map_err(|_| {
Error::custom(format!("Invalid hex value {}.", value).as_str())
})?,
};
Ok($name(value))
}
fn visit_string<E>(&mut self, value: String) -> Result<Self::Value, E> where E: Error {
self.visit_str(value.as_ref())
}
}
deserializer.deserialize(HashVisitor)
}
}
impl Serialize for $name {
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error> where S: Serializer {
let mut hex = "0x".to_owned();
hex.push_str(&self.0.to_hex());
serializer.serialize_str(&hex)
}
}
}
}
impl_hash!(H64, Hash64);
impl_hash!(Address, Hash160);
impl_hash!(H256, Hash256);
impl_hash!(H520, Hash520);
impl_hash!(Bloom, Hash2048);
#[cfg(test)]
mod test {
use std::str::FromStr;
use serde_json;
use util::hash;
use hash::H256;
#[test]
fn hash_deserialization() {
let s = r#"["", "5a39ed1020c04d4d84539975b893a4e7c53eab6c2965db8bc3468093a31bc5ae"]"#;
let deserialized: Vec<H256> = serde_json::from_str(s).unwrap();
assert_eq!(deserialized, vec![
H256(hash::H256::from(0)),
H256(hash::H256::from_str("5a39ed1020c04d4d84539975b893a4e7c53eab6c2965db8bc3468093a31bc5ae").unwrap())
]);
}
#[test]
fn hash_into() |
}
| {
assert_eq!(hash::H256::from(0), H256(hash::H256::from(0)).into());
} | identifier_body |
hash.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity 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 General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Lenient hash json deserialization for test json files.
use std::str::FromStr;
use serde::{Deserialize, Deserializer, Serialize, Serializer, Error};
use serde::de::Visitor;
use rustc_serialize::hex::ToHex;
use util::hash::{H64 as Hash64, H160 as Hash160, H256 as Hash256, H520 as Hash520, H2048 as Hash2048};
macro_rules! impl_hash {
($name: ident, $inner: ident) => {
/// Lenient hash json deserialization for test json files.
#[derive(Default, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Clone)]
pub struct $name(pub $inner);
impl Into<$inner> for $name {
fn into(self) -> $inner {
self.0
}
}
impl From<$inner> for $name {
fn from(i: $inner) -> Self {
$name(i)
}
}
impl Deserialize for $name {
fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
where D: Deserializer {
struct HashVisitor;
impl Visitor for HashVisitor {
type Value = $name;
fn visit_str<E>(&mut self, value: &str) -> Result<Self::Value, E> where E: Error {
let value = match value.len() {
0 => $inner::from(0),
2 if value == "0x" => $inner::from(0),
_ if value.starts_with("0x") => $inner::from_str(&value[2..]).map_err(|_| {
Error::custom(format!("Invalid hex value {}.", value).as_str())
})?,
_ => $inner::from_str(value).map_err(|_| {
Error::custom(format!("Invalid hex value {}.", value).as_str())
})?,
};
Ok($name(value))
}
fn visit_string<E>(&mut self, value: String) -> Result<Self::Value, E> where E: Error {
self.visit_str(value.as_ref())
}
}
deserializer.deserialize(HashVisitor)
}
} | let mut hex = "0x".to_owned();
hex.push_str(&self.0.to_hex());
serializer.serialize_str(&hex)
}
}
}
}
impl_hash!(H64, Hash64);
impl_hash!(Address, Hash160);
impl_hash!(H256, Hash256);
impl_hash!(H520, Hash520);
impl_hash!(Bloom, Hash2048);
#[cfg(test)]
mod test {
use std::str::FromStr;
use serde_json;
use util::hash;
use hash::H256;
#[test]
fn hash_deserialization() {
let s = r#"["", "5a39ed1020c04d4d84539975b893a4e7c53eab6c2965db8bc3468093a31bc5ae"]"#;
let deserialized: Vec<H256> = serde_json::from_str(s).unwrap();
assert_eq!(deserialized, vec![
H256(hash::H256::from(0)),
H256(hash::H256::from_str("5a39ed1020c04d4d84539975b893a4e7c53eab6c2965db8bc3468093a31bc5ae").unwrap())
]);
}
#[test]
fn hash_into() {
assert_eq!(hash::H256::from(0), H256(hash::H256::from(0)).into());
}
} |
impl Serialize for $name {
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error> where S: Serializer { | random_line_split |
hash.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity 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 General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Lenient hash json deserialization for test json files.
use std::str::FromStr;
use serde::{Deserialize, Deserializer, Serialize, Serializer, Error};
use serde::de::Visitor;
use rustc_serialize::hex::ToHex;
use util::hash::{H64 as Hash64, H160 as Hash160, H256 as Hash256, H520 as Hash520, H2048 as Hash2048};
macro_rules! impl_hash {
($name: ident, $inner: ident) => {
/// Lenient hash json deserialization for test json files.
#[derive(Default, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Clone)]
pub struct $name(pub $inner);
impl Into<$inner> for $name {
fn into(self) -> $inner {
self.0
}
}
impl From<$inner> for $name {
fn from(i: $inner) -> Self {
$name(i)
}
}
impl Deserialize for $name {
fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
where D: Deserializer {
struct HashVisitor;
impl Visitor for HashVisitor {
type Value = $name;
fn visit_str<E>(&mut self, value: &str) -> Result<Self::Value, E> where E: Error {
let value = match value.len() {
0 => $inner::from(0),
2 if value == "0x" => $inner::from(0),
_ if value.starts_with("0x") => $inner::from_str(&value[2..]).map_err(|_| {
Error::custom(format!("Invalid hex value {}.", value).as_str())
})?,
_ => $inner::from_str(value).map_err(|_| {
Error::custom(format!("Invalid hex value {}.", value).as_str())
})?,
};
Ok($name(value))
}
fn visit_string<E>(&mut self, value: String) -> Result<Self::Value, E> where E: Error {
self.visit_str(value.as_ref())
}
}
deserializer.deserialize(HashVisitor)
}
}
impl Serialize for $name {
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error> where S: Serializer {
let mut hex = "0x".to_owned();
hex.push_str(&self.0.to_hex());
serializer.serialize_str(&hex)
}
}
}
}
impl_hash!(H64, Hash64);
impl_hash!(Address, Hash160);
impl_hash!(H256, Hash256);
impl_hash!(H520, Hash520);
impl_hash!(Bloom, Hash2048);
#[cfg(test)]
mod test {
use std::str::FromStr;
use serde_json;
use util::hash;
use hash::H256;
#[test]
fn hash_deserialization() {
let s = r#"["", "5a39ed1020c04d4d84539975b893a4e7c53eab6c2965db8bc3468093a31bc5ae"]"#;
let deserialized: Vec<H256> = serde_json::from_str(s).unwrap();
assert_eq!(deserialized, vec![
H256(hash::H256::from(0)),
H256(hash::H256::from_str("5a39ed1020c04d4d84539975b893a4e7c53eab6c2965db8bc3468093a31bc5ae").unwrap())
]);
}
#[test]
fn | () {
assert_eq!(hash::H256::from(0), H256(hash::H256::from(0)).into());
}
}
| hash_into | identifier_name |
read_until.rs | use futures_core::future::Future;
use futures_core::ready;
use futures_core::task::{Context, Poll};
use futures_io::AsyncBufRead;
use std::io;
use std::mem;
use std::pin::Pin;
/// Future for the [`read_until`](super::AsyncBufReadExt::read_until) method.
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct ReadUntil<'a, R:?Sized> {
reader: &'a mut R,
byte: u8,
buf: &'a mut Vec<u8>,
read: usize,
}
impl<R:?Sized + Unpin> Unpin for ReadUntil<'_, R> {}
impl<'a, R: AsyncBufRead +?Sized + Unpin> ReadUntil<'a, R> {
pub(super) fn new(reader: &'a mut R, byte: u8, buf: &'a mut Vec<u8>) -> Self {
Self { reader, byte, buf, read: 0 }
}
}
pub(super) fn read_until_internal<R: AsyncBufRead +?Sized>(
mut reader: Pin<&mut R>,
cx: &mut Context<'_>,
byte: u8,
buf: &mut Vec<u8>,
read: &mut usize,
) -> Poll<io::Result<usize>> {
loop {
let (done, used) = {
let available = ready!(reader.as_mut().poll_fill_buf(cx))?;
if let Some(i) = memchr::memchr(byte, available) | else {
buf.extend_from_slice(available);
(false, available.len())
}
};
reader.as_mut().consume(used);
*read += used;
if done || used == 0 {
return Poll::Ready(Ok(mem::replace(read, 0)));
}
}
}
impl<R: AsyncBufRead +?Sized + Unpin> Future for ReadUntil<'_, R> {
type Output = io::Result<usize>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let Self { reader, byte, buf, read } = &mut *self;
read_until_internal(Pin::new(reader), cx, *byte, buf, read)
}
}
| {
buf.extend_from_slice(&available[..=i]);
(true, i + 1)
} | conditional_block |
read_until.rs | use futures_core::future::Future;
use futures_core::ready;
use futures_core::task::{Context, Poll};
use futures_io::AsyncBufRead;
use std::io;
use std::mem;
use std::pin::Pin;
/// Future for the [`read_until`](super::AsyncBufReadExt::read_until) method.
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"] | read: usize,
}
impl<R:?Sized + Unpin> Unpin for ReadUntil<'_, R> {}
impl<'a, R: AsyncBufRead +?Sized + Unpin> ReadUntil<'a, R> {
pub(super) fn new(reader: &'a mut R, byte: u8, buf: &'a mut Vec<u8>) -> Self {
Self { reader, byte, buf, read: 0 }
}
}
pub(super) fn read_until_internal<R: AsyncBufRead +?Sized>(
mut reader: Pin<&mut R>,
cx: &mut Context<'_>,
byte: u8,
buf: &mut Vec<u8>,
read: &mut usize,
) -> Poll<io::Result<usize>> {
loop {
let (done, used) = {
let available = ready!(reader.as_mut().poll_fill_buf(cx))?;
if let Some(i) = memchr::memchr(byte, available) {
buf.extend_from_slice(&available[..=i]);
(true, i + 1)
} else {
buf.extend_from_slice(available);
(false, available.len())
}
};
reader.as_mut().consume(used);
*read += used;
if done || used == 0 {
return Poll::Ready(Ok(mem::replace(read, 0)));
}
}
}
impl<R: AsyncBufRead +?Sized + Unpin> Future for ReadUntil<'_, R> {
type Output = io::Result<usize>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let Self { reader, byte, buf, read } = &mut *self;
read_until_internal(Pin::new(reader), cx, *byte, buf, read)
}
} | pub struct ReadUntil<'a, R: ?Sized> {
reader: &'a mut R,
byte: u8,
buf: &'a mut Vec<u8>, | random_line_split |
read_until.rs | use futures_core::future::Future;
use futures_core::ready;
use futures_core::task::{Context, Poll};
use futures_io::AsyncBufRead;
use std::io;
use std::mem;
use std::pin::Pin;
/// Future for the [`read_until`](super::AsyncBufReadExt::read_until) method.
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct ReadUntil<'a, R:?Sized> {
reader: &'a mut R,
byte: u8,
buf: &'a mut Vec<u8>,
read: usize,
}
impl<R:?Sized + Unpin> Unpin for ReadUntil<'_, R> {}
impl<'a, R: AsyncBufRead +?Sized + Unpin> ReadUntil<'a, R> {
pub(super) fn new(reader: &'a mut R, byte: u8, buf: &'a mut Vec<u8>) -> Self {
Self { reader, byte, buf, read: 0 }
}
}
pub(super) fn read_until_internal<R: AsyncBufRead +?Sized>(
mut reader: Pin<&mut R>,
cx: &mut Context<'_>,
byte: u8,
buf: &mut Vec<u8>,
read: &mut usize,
) -> Poll<io::Result<usize>> |
impl<R: AsyncBufRead +?Sized + Unpin> Future for ReadUntil<'_, R> {
type Output = io::Result<usize>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let Self { reader, byte, buf, read } = &mut *self;
read_until_internal(Pin::new(reader), cx, *byte, buf, read)
}
}
| {
loop {
let (done, used) = {
let available = ready!(reader.as_mut().poll_fill_buf(cx))?;
if let Some(i) = memchr::memchr(byte, available) {
buf.extend_from_slice(&available[..=i]);
(true, i + 1)
} else {
buf.extend_from_slice(available);
(false, available.len())
}
};
reader.as_mut().consume(used);
*read += used;
if done || used == 0 {
return Poll::Ready(Ok(mem::replace(read, 0)));
}
}
} | identifier_body |
read_until.rs | use futures_core::future::Future;
use futures_core::ready;
use futures_core::task::{Context, Poll};
use futures_io::AsyncBufRead;
use std::io;
use std::mem;
use std::pin::Pin;
/// Future for the [`read_until`](super::AsyncBufReadExt::read_until) method.
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct ReadUntil<'a, R:?Sized> {
reader: &'a mut R,
byte: u8,
buf: &'a mut Vec<u8>,
read: usize,
}
impl<R:?Sized + Unpin> Unpin for ReadUntil<'_, R> {}
impl<'a, R: AsyncBufRead +?Sized + Unpin> ReadUntil<'a, R> {
pub(super) fn new(reader: &'a mut R, byte: u8, buf: &'a mut Vec<u8>) -> Self {
Self { reader, byte, buf, read: 0 }
}
}
pub(super) fn | <R: AsyncBufRead +?Sized>(
mut reader: Pin<&mut R>,
cx: &mut Context<'_>,
byte: u8,
buf: &mut Vec<u8>,
read: &mut usize,
) -> Poll<io::Result<usize>> {
loop {
let (done, used) = {
let available = ready!(reader.as_mut().poll_fill_buf(cx))?;
if let Some(i) = memchr::memchr(byte, available) {
buf.extend_from_slice(&available[..=i]);
(true, i + 1)
} else {
buf.extend_from_slice(available);
(false, available.len())
}
};
reader.as_mut().consume(used);
*read += used;
if done || used == 0 {
return Poll::Ready(Ok(mem::replace(read, 0)));
}
}
}
impl<R: AsyncBufRead +?Sized + Unpin> Future for ReadUntil<'_, R> {
type Output = io::Result<usize>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let Self { reader, byte, buf, read } = &mut *self;
read_until_internal(Pin::new(reader), cx, *byte, buf, read)
}
}
| read_until_internal | identifier_name |
activity.rs | use event::{Event, React};
use failure::Error;
use framework::context::{RenderContextView, State, UpdateContextView};
use framework::FrameworkError;
use render::MetaRenderer;
pub enum Transition<T, R>
where
T: State,
R: MetaRenderer,
{
None,
Push(BoxActivity<T, R>),
Pop,
Abort,
}
impl<T, R> Transition<T, R>
where
T: State,
R: MetaRenderer,
{
fn is_abort(&self) -> bool {
match *self {
Transition::Abort => true,
_ => false,
}
}
}
pub type BoxActivity<T, R> = Box<Activity<T, R>>;
pub type UpdateResult<T, R> = Result<Transition<T, R>, FrameworkError>;
pub type RenderResult = Result<(), FrameworkError>;
pub trait Activity<T, R>: React
where
T: State,
R: MetaRenderer,
{
// TODO: It could be useful to extract `update` and `render` into generic
// traits of their own, but this would require associated types and
// there is currently no good way to bind those (until trait aliases
// land). Consider refactoring this once that is possible and clean.
fn update(&mut self, context: &mut UpdateContextView<State = T>) -> UpdateResult<T, R>;
fn render(&mut self, context: &mut RenderContextView<R, State = T>) -> RenderResult;
fn suspend(&mut self) {}
fn resume(&mut self) {}
fn stop(&mut self) {}
}
pub struct ActivityStack<T, R>
where
T: State,
R: MetaRenderer,
{
stack: Vec<BoxActivity<T, R>>,
}
impl<T, R> ActivityStack<T, R>
where
T: State,
R: MetaRenderer,
{
pub fn new(activity: BoxActivity<T, R>) -> Self {
ActivityStack {
stack: vec![activity],
}
}
pub fn update<C>(&mut self, context: &mut C) -> Result<bool, Error>
where
C: UpdateContextView<State = T>,
{
let transition = self.peek_mut()
.map_or(Ok(Transition::Abort), |activity| activity.update(context))?;
let signal =!transition.is_abort();
match transition {
Transition::Push(activity) => {
self.push(activity);
}
Transition::Pop => {
self.pop();
}
Transition::Abort => {
self.abort();
}
_ => {}
}
Ok(signal)
} | pub fn render<C>(&mut self, context: &mut C) -> Result<(), Error>
where
C: RenderContextView<R, State = T>,
{
self.peek_mut().map_or(Ok(()), |activity| {
activity.render(context).map_err(|error| error.into())
})
}
fn peek_mut(&mut self) -> Option<&mut Activity<T, R>> {
if let Some(activity) = self.stack.last_mut() {
// Cannot use `map`.
Some(activity.as_mut())
}
else {
None
}
}
fn push(&mut self, activity: BoxActivity<T, R>) {
if let Some(activity) = self.peek_mut() {
activity.suspend();
}
self.stack.push(activity);
}
fn pop(&mut self) -> bool {
self.stack
.pop()
.map(|mut activity| {
activity.stop();
if let Some(activity) = self.peek_mut() {
activity.resume()
}
})
.is_some()
}
fn abort(&mut self) {
while self.pop() {}
}
}
impl<T, R> Drop for ActivityStack<T, R>
where
T: State,
R: MetaRenderer,
{
fn drop(&mut self) {
self.abort();
}
}
impl<T, R> React for ActivityStack<T, R>
where
T: State,
R: MetaRenderer,
{
fn react(&mut self, event: &Event) {
if let Some(activity) = self.peek_mut() {
activity.react(event);
}
}
} | random_line_split |
|
activity.rs | use event::{Event, React};
use failure::Error;
use framework::context::{RenderContextView, State, UpdateContextView};
use framework::FrameworkError;
use render::MetaRenderer;
pub enum Transition<T, R>
where
T: State,
R: MetaRenderer,
{
None,
Push(BoxActivity<T, R>),
Pop,
Abort,
}
impl<T, R> Transition<T, R>
where
T: State,
R: MetaRenderer,
{
fn is_abort(&self) -> bool {
match *self {
Transition::Abort => true,
_ => false,
}
}
}
pub type BoxActivity<T, R> = Box<Activity<T, R>>;
pub type UpdateResult<T, R> = Result<Transition<T, R>, FrameworkError>;
pub type RenderResult = Result<(), FrameworkError>;
pub trait Activity<T, R>: React
where
T: State,
R: MetaRenderer,
{
// TODO: It could be useful to extract `update` and `render` into generic
// traits of their own, but this would require associated types and
// there is currently no good way to bind those (until trait aliases
// land). Consider refactoring this once that is possible and clean.
fn update(&mut self, context: &mut UpdateContextView<State = T>) -> UpdateResult<T, R>;
fn render(&mut self, context: &mut RenderContextView<R, State = T>) -> RenderResult;
fn suspend(&mut self) {}
fn | (&mut self) {}
fn stop(&mut self) {}
}
pub struct ActivityStack<T, R>
where
T: State,
R: MetaRenderer,
{
stack: Vec<BoxActivity<T, R>>,
}
impl<T, R> ActivityStack<T, R>
where
T: State,
R: MetaRenderer,
{
pub fn new(activity: BoxActivity<T, R>) -> Self {
ActivityStack {
stack: vec![activity],
}
}
pub fn update<C>(&mut self, context: &mut C) -> Result<bool, Error>
where
C: UpdateContextView<State = T>,
{
let transition = self.peek_mut()
.map_or(Ok(Transition::Abort), |activity| activity.update(context))?;
let signal =!transition.is_abort();
match transition {
Transition::Push(activity) => {
self.push(activity);
}
Transition::Pop => {
self.pop();
}
Transition::Abort => {
self.abort();
}
_ => {}
}
Ok(signal)
}
pub fn render<C>(&mut self, context: &mut C) -> Result<(), Error>
where
C: RenderContextView<R, State = T>,
{
self.peek_mut().map_or(Ok(()), |activity| {
activity.render(context).map_err(|error| error.into())
})
}
fn peek_mut(&mut self) -> Option<&mut Activity<T, R>> {
if let Some(activity) = self.stack.last_mut() {
// Cannot use `map`.
Some(activity.as_mut())
}
else {
None
}
}
fn push(&mut self, activity: BoxActivity<T, R>) {
if let Some(activity) = self.peek_mut() {
activity.suspend();
}
self.stack.push(activity);
}
fn pop(&mut self) -> bool {
self.stack
.pop()
.map(|mut activity| {
activity.stop();
if let Some(activity) = self.peek_mut() {
activity.resume()
}
})
.is_some()
}
fn abort(&mut self) {
while self.pop() {}
}
}
impl<T, R> Drop for ActivityStack<T, R>
where
T: State,
R: MetaRenderer,
{
fn drop(&mut self) {
self.abort();
}
}
impl<T, R> React for ActivityStack<T, R>
where
T: State,
R: MetaRenderer,
{
fn react(&mut self, event: &Event) {
if let Some(activity) = self.peek_mut() {
activity.react(event);
}
}
}
| resume | identifier_name |
activity.rs | use event::{Event, React};
use failure::Error;
use framework::context::{RenderContextView, State, UpdateContextView};
use framework::FrameworkError;
use render::MetaRenderer;
pub enum Transition<T, R>
where
T: State,
R: MetaRenderer,
{
None,
Push(BoxActivity<T, R>),
Pop,
Abort,
}
impl<T, R> Transition<T, R>
where
T: State,
R: MetaRenderer,
{
fn is_abort(&self) -> bool {
match *self {
Transition::Abort => true,
_ => false,
}
}
}
pub type BoxActivity<T, R> = Box<Activity<T, R>>;
pub type UpdateResult<T, R> = Result<Transition<T, R>, FrameworkError>;
pub type RenderResult = Result<(), FrameworkError>;
pub trait Activity<T, R>: React
where
T: State,
R: MetaRenderer,
{
// TODO: It could be useful to extract `update` and `render` into generic
// traits of their own, but this would require associated types and
// there is currently no good way to bind those (until trait aliases
// land). Consider refactoring this once that is possible and clean.
fn update(&mut self, context: &mut UpdateContextView<State = T>) -> UpdateResult<T, R>;
fn render(&mut self, context: &mut RenderContextView<R, State = T>) -> RenderResult;
fn suspend(&mut self) {}
fn resume(&mut self) |
fn stop(&mut self) {}
}
pub struct ActivityStack<T, R>
where
T: State,
R: MetaRenderer,
{
stack: Vec<BoxActivity<T, R>>,
}
impl<T, R> ActivityStack<T, R>
where
T: State,
R: MetaRenderer,
{
pub fn new(activity: BoxActivity<T, R>) -> Self {
ActivityStack {
stack: vec![activity],
}
}
pub fn update<C>(&mut self, context: &mut C) -> Result<bool, Error>
where
C: UpdateContextView<State = T>,
{
let transition = self.peek_mut()
.map_or(Ok(Transition::Abort), |activity| activity.update(context))?;
let signal =!transition.is_abort();
match transition {
Transition::Push(activity) => {
self.push(activity);
}
Transition::Pop => {
self.pop();
}
Transition::Abort => {
self.abort();
}
_ => {}
}
Ok(signal)
}
pub fn render<C>(&mut self, context: &mut C) -> Result<(), Error>
where
C: RenderContextView<R, State = T>,
{
self.peek_mut().map_or(Ok(()), |activity| {
activity.render(context).map_err(|error| error.into())
})
}
fn peek_mut(&mut self) -> Option<&mut Activity<T, R>> {
if let Some(activity) = self.stack.last_mut() {
// Cannot use `map`.
Some(activity.as_mut())
}
else {
None
}
}
fn push(&mut self, activity: BoxActivity<T, R>) {
if let Some(activity) = self.peek_mut() {
activity.suspend();
}
self.stack.push(activity);
}
fn pop(&mut self) -> bool {
self.stack
.pop()
.map(|mut activity| {
activity.stop();
if let Some(activity) = self.peek_mut() {
activity.resume()
}
})
.is_some()
}
fn abort(&mut self) {
while self.pop() {}
}
}
impl<T, R> Drop for ActivityStack<T, R>
where
T: State,
R: MetaRenderer,
{
fn drop(&mut self) {
self.abort();
}
}
impl<T, R> React for ActivityStack<T, R>
where
T: State,
R: MetaRenderer,
{
fn react(&mut self, event: &Event) {
if let Some(activity) = self.peek_mut() {
activity.react(event);
}
}
}
| {} | identifier_body |
activity.rs | use event::{Event, React};
use failure::Error;
use framework::context::{RenderContextView, State, UpdateContextView};
use framework::FrameworkError;
use render::MetaRenderer;
pub enum Transition<T, R>
where
T: State,
R: MetaRenderer,
{
None,
Push(BoxActivity<T, R>),
Pop,
Abort,
}
impl<T, R> Transition<T, R>
where
T: State,
R: MetaRenderer,
{
fn is_abort(&self) -> bool {
match *self {
Transition::Abort => true,
_ => false,
}
}
}
pub type BoxActivity<T, R> = Box<Activity<T, R>>;
pub type UpdateResult<T, R> = Result<Transition<T, R>, FrameworkError>;
pub type RenderResult = Result<(), FrameworkError>;
pub trait Activity<T, R>: React
where
T: State,
R: MetaRenderer,
{
// TODO: It could be useful to extract `update` and `render` into generic
// traits of their own, but this would require associated types and
// there is currently no good way to bind those (until trait aliases
// land). Consider refactoring this once that is possible and clean.
fn update(&mut self, context: &mut UpdateContextView<State = T>) -> UpdateResult<T, R>;
fn render(&mut self, context: &mut RenderContextView<R, State = T>) -> RenderResult;
fn suspend(&mut self) {}
fn resume(&mut self) {}
fn stop(&mut self) {}
}
pub struct ActivityStack<T, R>
where
T: State,
R: MetaRenderer,
{
stack: Vec<BoxActivity<T, R>>,
}
impl<T, R> ActivityStack<T, R>
where
T: State,
R: MetaRenderer,
{
pub fn new(activity: BoxActivity<T, R>) -> Self {
ActivityStack {
stack: vec![activity],
}
}
pub fn update<C>(&mut self, context: &mut C) -> Result<bool, Error>
where
C: UpdateContextView<State = T>,
{
let transition = self.peek_mut()
.map_or(Ok(Transition::Abort), |activity| activity.update(context))?;
let signal =!transition.is_abort();
match transition {
Transition::Push(activity) => {
self.push(activity);
}
Transition::Pop => {
self.pop();
}
Transition::Abort => {
self.abort();
}
_ => {}
}
Ok(signal)
}
pub fn render<C>(&mut self, context: &mut C) -> Result<(), Error>
where
C: RenderContextView<R, State = T>,
{
self.peek_mut().map_or(Ok(()), |activity| {
activity.render(context).map_err(|error| error.into())
})
}
fn peek_mut(&mut self) -> Option<&mut Activity<T, R>> {
if let Some(activity) = self.stack.last_mut() |
else {
None
}
}
fn push(&mut self, activity: BoxActivity<T, R>) {
if let Some(activity) = self.peek_mut() {
activity.suspend();
}
self.stack.push(activity);
}
fn pop(&mut self) -> bool {
self.stack
.pop()
.map(|mut activity| {
activity.stop();
if let Some(activity) = self.peek_mut() {
activity.resume()
}
})
.is_some()
}
fn abort(&mut self) {
while self.pop() {}
}
}
impl<T, R> Drop for ActivityStack<T, R>
where
T: State,
R: MetaRenderer,
{
fn drop(&mut self) {
self.abort();
}
}
impl<T, R> React for ActivityStack<T, R>
where
T: State,
R: MetaRenderer,
{
fn react(&mut self, event: &Event) {
if let Some(activity) = self.peek_mut() {
activity.react(event);
}
}
}
| {
// Cannot use `map`.
Some(activity.as_mut())
} | conditional_block |
notify.rs | use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Instant;
use crossbeam_channel::Sender;
use dbus::ffidisp::stdintf::org_freedesktop_dbus::{Properties, PropertiesPropertiesChanged};
use dbus::ffidisp::{BusType, Connection};
use dbus::message::SignalArgs;
use serde_derive::Deserialize;
use crate::blocks::{Block, ConfigBlock, Update};
use crate::config::SharedConfig;
use crate::errors::*;
use crate::formatting::value::Value;
use crate::formatting::FormatTemplate;
use crate::protocol::i3bar_event::{I3BarEvent, MouseButton};
use crate::scheduler::Task;
use crate::widgets::text::TextWidget;
use crate::widgets::I3BarWidget;
// TODO
// Add driver option so can choose between dunst, mako, etc.
pub struct Notify {
id: usize,
paused: Arc<Mutex<i64>>,
format: FormatTemplate,
output: TextWidget,
}
#[derive(Deserialize, Debug, Default, Clone)]
#[serde(deny_unknown_fields, default)]
pub struct NotifyConfig {
/// Format string which describes the output of this block.
pub format: FormatTemplate,
}
impl ConfigBlock for Notify {
type Config = NotifyConfig;
fn new(
id: usize,
block_config: Self::Config,
shared_config: SharedConfig,
send: Sender<Task>,
) -> Result<Self> {
let c = Connection::get_private(BusType::Session)
.block_error("notify", "Failed to establish D-Bus connection")?;
let p = c.with_path(
"org.freedesktop.Notifications",
"/org/freedesktop/Notifications",
5000,
);
let initial_state: bool = p
.get("org.dunstproject.cmd0", "paused")
.block_error("notify", "Failed to get dunst state. Is it running?")?;
let icon = if initial_state { "bell-slash" } else { "bell" };
// TODO: revisit this lint
#[allow(clippy::mutex_atomic)]
let state = Arc::new(Mutex::new(initial_state as i64));
let state_copy = state.clone();
thread::Builder::new()
.name("notify".into())
.spawn(move || {
let c = Connection::get_private(BusType::Session)
.expect("Failed to establish D-Bus connection in thread");
let matched_signal = PropertiesPropertiesChanged::match_str(
Some(&"org.freedesktop.Notifications".into()),
None,
);
c.add_match(&matched_signal).unwrap();
loop { | for msg in c.incoming(1000) {
if let Some(signal) = PropertiesPropertiesChanged::from_message(&msg) {
let value = signal.changed_properties.get("paused").unwrap();
let status = &value.0.as_i64().unwrap();
let mut paused = state_copy.lock().unwrap();
*paused = *status;
// Tell block to update now.
send.send(Task {
id,
update_time: Instant::now(),
})
.unwrap();
}
}
}
})
.unwrap();
Ok(Notify {
id,
paused: state,
format: block_config.format.with_default("")?,
output: TextWidget::new(id, 0, shared_config).with_icon(icon)?,
})
}
}
impl Block for Notify {
fn id(&self) -> usize {
self.id
}
fn update(&mut self) -> Result<Option<Update>> {
let paused = *self
.paused
.lock()
.block_error("notify", "failed to acquire lock for `state`")?;
let values = map!(
"state" => Value::from_string(paused.to_string())
);
self.output.set_texts(self.format.render(&values)?);
let icon = if paused == 1 { "bell-slash" } else { "bell" };
self.output.set_icon(icon)?;
Ok(None)
}
// Returns the view of the block, comprised of widgets.
fn view(&self) -> Vec<&dyn I3BarWidget> {
vec![&self.output]
}
fn click(&mut self, e: &I3BarEvent) -> Result<()> {
if let MouseButton::Left = e.button {
let c = Connection::get_private(BusType::Session)
.block_error("notify", "Failed to establish D-Bus connection")?;
let p = c.with_path(
"org.freedesktop.Notifications",
"/org/freedesktop/Notifications",
5000,
);
let paused = *self
.paused
.lock()
.block_error("notify", "failed to acquire lock")?;
if paused == 1 {
p.set("org.dunstproject.cmd0", "paused", false)
.block_error("notify", "Failed to query D-Bus")?;
} else {
p.set("org.dunstproject.cmd0", "paused", true)
.block_error("notify", "Failed to query D-Bus")?;
}
// block will auto-update due to monitoring the bus
}
Ok(())
}
} | random_line_split |
|
notify.rs | use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Instant;
use crossbeam_channel::Sender;
use dbus::ffidisp::stdintf::org_freedesktop_dbus::{Properties, PropertiesPropertiesChanged};
use dbus::ffidisp::{BusType, Connection};
use dbus::message::SignalArgs;
use serde_derive::Deserialize;
use crate::blocks::{Block, ConfigBlock, Update};
use crate::config::SharedConfig;
use crate::errors::*;
use crate::formatting::value::Value;
use crate::formatting::FormatTemplate;
use crate::protocol::i3bar_event::{I3BarEvent, MouseButton};
use crate::scheduler::Task;
use crate::widgets::text::TextWidget;
use crate::widgets::I3BarWidget;
// TODO
// Add driver option so can choose between dunst, mako, etc.
pub struct Notify {
id: usize,
paused: Arc<Mutex<i64>>,
format: FormatTemplate,
output: TextWidget,
}
#[derive(Deserialize, Debug, Default, Clone)]
#[serde(deny_unknown_fields, default)]
pub struct NotifyConfig {
/// Format string which describes the output of this block.
pub format: FormatTemplate,
}
impl ConfigBlock for Notify {
type Config = NotifyConfig;
fn new(
id: usize,
block_config: Self::Config,
shared_config: SharedConfig,
send: Sender<Task>,
) -> Result<Self> {
let c = Connection::get_private(BusType::Session)
.block_error("notify", "Failed to establish D-Bus connection")?;
let p = c.with_path(
"org.freedesktop.Notifications",
"/org/freedesktop/Notifications",
5000,
);
let initial_state: bool = p
.get("org.dunstproject.cmd0", "paused")
.block_error("notify", "Failed to get dunst state. Is it running?")?;
let icon = if initial_state { "bell-slash" } else { "bell" };
// TODO: revisit this lint
#[allow(clippy::mutex_atomic)]
let state = Arc::new(Mutex::new(initial_state as i64));
let state_copy = state.clone();
thread::Builder::new()
.name("notify".into())
.spawn(move || {
let c = Connection::get_private(BusType::Session)
.expect("Failed to establish D-Bus connection in thread");
let matched_signal = PropertiesPropertiesChanged::match_str(
Some(&"org.freedesktop.Notifications".into()),
None,
);
c.add_match(&matched_signal).unwrap();
loop {
for msg in c.incoming(1000) {
if let Some(signal) = PropertiesPropertiesChanged::from_message(&msg) {
let value = signal.changed_properties.get("paused").unwrap();
let status = &value.0.as_i64().unwrap();
let mut paused = state_copy.lock().unwrap();
*paused = *status;
// Tell block to update now.
send.send(Task {
id,
update_time: Instant::now(),
})
.unwrap();
}
}
}
})
.unwrap();
Ok(Notify {
id,
paused: state,
format: block_config.format.with_default("")?,
output: TextWidget::new(id, 0, shared_config).with_icon(icon)?,
})
}
}
impl Block for Notify {
fn id(&self) -> usize {
self.id
}
fn update(&mut self) -> Result<Option<Update>> {
let paused = *self
.paused
.lock()
.block_error("notify", "failed to acquire lock for `state`")?;
let values = map!(
"state" => Value::from_string(paused.to_string())
);
self.output.set_texts(self.format.render(&values)?);
let icon = if paused == 1 { "bell-slash" } else { "bell" };
self.output.set_icon(icon)?;
Ok(None)
}
// Returns the view of the block, comprised of widgets.
fn | (&self) -> Vec<&dyn I3BarWidget> {
vec![&self.output]
}
fn click(&mut self, e: &I3BarEvent) -> Result<()> {
if let MouseButton::Left = e.button {
let c = Connection::get_private(BusType::Session)
.block_error("notify", "Failed to establish D-Bus connection")?;
let p = c.with_path(
"org.freedesktop.Notifications",
"/org/freedesktop/Notifications",
5000,
);
let paused = *self
.paused
.lock()
.block_error("notify", "failed to acquire lock")?;
if paused == 1 {
p.set("org.dunstproject.cmd0", "paused", false)
.block_error("notify", "Failed to query D-Bus")?;
} else {
p.set("org.dunstproject.cmd0", "paused", true)
.block_error("notify", "Failed to query D-Bus")?;
}
// block will auto-update due to monitoring the bus
}
Ok(())
}
}
| view | identifier_name |
notify.rs | use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Instant;
use crossbeam_channel::Sender;
use dbus::ffidisp::stdintf::org_freedesktop_dbus::{Properties, PropertiesPropertiesChanged};
use dbus::ffidisp::{BusType, Connection};
use dbus::message::SignalArgs;
use serde_derive::Deserialize;
use crate::blocks::{Block, ConfigBlock, Update};
use crate::config::SharedConfig;
use crate::errors::*;
use crate::formatting::value::Value;
use crate::formatting::FormatTemplate;
use crate::protocol::i3bar_event::{I3BarEvent, MouseButton};
use crate::scheduler::Task;
use crate::widgets::text::TextWidget;
use crate::widgets::I3BarWidget;
// TODO
// Add driver option so can choose between dunst, mako, etc.
pub struct Notify {
id: usize,
paused: Arc<Mutex<i64>>,
format: FormatTemplate,
output: TextWidget,
}
#[derive(Deserialize, Debug, Default, Clone)]
#[serde(deny_unknown_fields, default)]
pub struct NotifyConfig {
/// Format string which describes the output of this block.
pub format: FormatTemplate,
}
impl ConfigBlock for Notify {
type Config = NotifyConfig;
fn new(
id: usize,
block_config: Self::Config,
shared_config: SharedConfig,
send: Sender<Task>,
) -> Result<Self> {
let c = Connection::get_private(BusType::Session)
.block_error("notify", "Failed to establish D-Bus connection")?;
let p = c.with_path(
"org.freedesktop.Notifications",
"/org/freedesktop/Notifications",
5000,
);
let initial_state: bool = p
.get("org.dunstproject.cmd0", "paused")
.block_error("notify", "Failed to get dunst state. Is it running?")?;
let icon = if initial_state { "bell-slash" } else { "bell" };
// TODO: revisit this lint
#[allow(clippy::mutex_atomic)]
let state = Arc::new(Mutex::new(initial_state as i64));
let state_copy = state.clone();
thread::Builder::new()
.name("notify".into())
.spawn(move || {
let c = Connection::get_private(BusType::Session)
.expect("Failed to establish D-Bus connection in thread");
let matched_signal = PropertiesPropertiesChanged::match_str(
Some(&"org.freedesktop.Notifications".into()),
None,
);
c.add_match(&matched_signal).unwrap();
loop {
for msg in c.incoming(1000) {
if let Some(signal) = PropertiesPropertiesChanged::from_message(&msg) {
let value = signal.changed_properties.get("paused").unwrap();
let status = &value.0.as_i64().unwrap();
let mut paused = state_copy.lock().unwrap();
*paused = *status;
// Tell block to update now.
send.send(Task {
id,
update_time: Instant::now(),
})
.unwrap();
}
}
}
})
.unwrap();
Ok(Notify {
id,
paused: state,
format: block_config.format.with_default("")?,
output: TextWidget::new(id, 0, shared_config).with_icon(icon)?,
})
}
}
impl Block for Notify {
fn id(&self) -> usize {
self.id
}
fn update(&mut self) -> Result<Option<Update>> {
let paused = *self
.paused
.lock()
.block_error("notify", "failed to acquire lock for `state`")?;
let values = map!(
"state" => Value::from_string(paused.to_string())
);
self.output.set_texts(self.format.render(&values)?);
let icon = if paused == 1 { "bell-slash" } else { "bell" };
self.output.set_icon(icon)?;
Ok(None)
}
// Returns the view of the block, comprised of widgets.
fn view(&self) -> Vec<&dyn I3BarWidget> {
vec![&self.output]
}
fn click(&mut self, e: &I3BarEvent) -> Result<()> {
if let MouseButton::Left = e.button {
let c = Connection::get_private(BusType::Session)
.block_error("notify", "Failed to establish D-Bus connection")?;
let p = c.with_path(
"org.freedesktop.Notifications",
"/org/freedesktop/Notifications",
5000,
);
let paused = *self
.paused
.lock()
.block_error("notify", "failed to acquire lock")?;
if paused == 1 | else {
p.set("org.dunstproject.cmd0", "paused", true)
.block_error("notify", "Failed to query D-Bus")?;
}
// block will auto-update due to monitoring the bus
}
Ok(())
}
}
| {
p.set("org.dunstproject.cmd0", "paused", false)
.block_error("notify", "Failed to query D-Bus")?;
} | conditional_block |
task-comm-4.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.
#![allow(dead_assignment)]
pub fn main() { test00(); }
fn test00() {
let mut r: int = 0;
let mut sum: int = 0;
let (tx, rx) = channel();
tx.send(1);
tx.send(2);
tx.send(3);
tx.send(4);
r = rx.recv();
sum += r;
println!("{}", r);
r = rx.recv();
sum += r;
println!("{}", r);
r = rx.recv();
sum += r;
println!("{}", r);
r = rx.recv();
sum += r;
println!("{}", r);
tx.send(5);
tx.send(6);
tx.send(7);
tx.send(8);
r = rx.recv();
sum += r;
println!("{}", r);
r = rx.recv();
sum += r;
println!("{}", r);
r = rx.recv();
sum += r; | println!("{}", r);
assert_eq!(sum, 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8);
} | println!("{}", r);
r = rx.recv();
sum += r; | random_line_split |
task-comm-4.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.
#![allow(dead_assignment)]
pub fn main() { test00(); }
fn | () {
let mut r: int = 0;
let mut sum: int = 0;
let (tx, rx) = channel();
tx.send(1);
tx.send(2);
tx.send(3);
tx.send(4);
r = rx.recv();
sum += r;
println!("{}", r);
r = rx.recv();
sum += r;
println!("{}", r);
r = rx.recv();
sum += r;
println!("{}", r);
r = rx.recv();
sum += r;
println!("{}", r);
tx.send(5);
tx.send(6);
tx.send(7);
tx.send(8);
r = rx.recv();
sum += r;
println!("{}", r);
r = rx.recv();
sum += r;
println!("{}", r);
r = rx.recv();
sum += r;
println!("{}", r);
r = rx.recv();
sum += r;
println!("{}", r);
assert_eq!(sum, 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8);
}
| test00 | identifier_name |
task-comm-4.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.
#![allow(dead_assignment)]
pub fn main() { test00(); }
fn test00() | tx.send(5);
tx.send(6);
tx.send(7);
tx.send(8);
r = rx.recv();
sum += r;
println!("{}", r);
r = rx.recv();
sum += r;
println!("{}", r);
r = rx.recv();
sum += r;
println!("{}", r);
r = rx.recv();
sum += r;
println!("{}", r);
assert_eq!(sum, 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8);
}
| {
let mut r: int = 0;
let mut sum: int = 0;
let (tx, rx) = channel();
tx.send(1);
tx.send(2);
tx.send(3);
tx.send(4);
r = rx.recv();
sum += r;
println!("{}", r);
r = rx.recv();
sum += r;
println!("{}", r);
r = rx.recv();
sum += r;
println!("{}", r);
r = rx.recv();
sum += r;
println!("{}", r); | identifier_body |
_common.rs | // Copyright 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.
use std::io;
use std::io::prelude::*;
use std::mem::transmute;
// Nothing up my sleeve: Just (PI - 3) in base 16.
#[allow(dead_code)]
pub const SEED: [u32; 3] = [0x243f_6a88, 0x85a3_08d3, 0x1319_8a2e];
pub fn validate(text: &str) | {
let mut out = io::stdout();
let x: f64 = text.parse().unwrap();
let f64_bytes: u64 = unsafe { transmute(x) };
let x: f32 = text.parse().unwrap();
let f32_bytes: u32 = unsafe { transmute(x) };
writeln!(&mut out, "{:016x} {:08x} {}", f64_bytes, f32_bytes, text).unwrap();
} | identifier_body |
|
_common.rs | // Copyright 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.
use std::io;
use std::io::prelude::*;
use std::mem::transmute;
// Nothing up my sleeve: Just (PI - 3) in base 16.
#[allow(dead_code)]
pub const SEED: [u32; 3] = [0x243f_6a88, 0x85a3_08d3, 0x1319_8a2e];
pub fn | (text: &str) {
let mut out = io::stdout();
let x: f64 = text.parse().unwrap();
let f64_bytes: u64 = unsafe { transmute(x) };
let x: f32 = text.parse().unwrap();
let f32_bytes: u32 = unsafe { transmute(x) };
writeln!(&mut out, "{:016x} {:08x} {}", f64_bytes, f32_bytes, text).unwrap();
}
| validate | identifier_name |
_common.rs | // Copyright 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 | use std::io;
use std::io::prelude::*;
use std::mem::transmute;
// Nothing up my sleeve: Just (PI - 3) in base 16.
#[allow(dead_code)]
pub const SEED: [u32; 3] = [0x243f_6a88, 0x85a3_08d3, 0x1319_8a2e];
pub fn validate(text: &str) {
let mut out = io::stdout();
let x: f64 = text.parse().unwrap();
let f64_bytes: u64 = unsafe { transmute(x) };
let x: f32 = text.parse().unwrap();
let f32_bytes: u32 = unsafe { transmute(x) };
writeln!(&mut out, "{:016x} {:08x} {}", f64_bytes, f32_bytes, text).unwrap();
} | // except according to those terms.
| random_line_split |
hostname.rs | extern crate getopts;
extern crate libc;
use getopts::{optflag, getopts, usage, OptGroup};
use libc::{c_char, c_int, size_t};
use std::io::stdio;
use std::os;
static HOSTNAME_MAX_LENGTH: uint = 256;
extern {
fn gethostname(name: *mut c_char, namelen: size_t) -> c_int;
}
fn main() {
let exit_status = run(os::args());
os::set_exit_status(exit_status);
}
fn usage_message(program: &String, options: &[OptGroup]) -> String {
let instructions = format!("Usage: {} [options] [HOSTNAME]", program);
usage(instructions.as_slice(), options)
}
fn run(args: Vec<String>) -> int {
let program = &args[0];
let parameters = [
optflag("V", "version", "Print the version number and exit"),
optflag("h", "help", "Print this help message")
];
let options = match getopts(args.tail(), parameters) {
Ok(options) => options,
Err(failure) => fail!(failure.to_string())
};
if options.opt_present("h") {
println(usage_message(program, parameters));
return 0;
}
if options.opt_present("V") {
println!("hostname 1.0.0");
return 0;
}
if options.free.len() == 1 {
err_println("hostname: you must be root to change the host name\n".to_string());
return 1;
}
match get_hostname() {
Ok(hostname) => println(hostname),
Err(error) => err_println(error)
}
return 0;
}
fn | () -> Result<String, String> {
let mut name = String::with_capacity(HOSTNAME_MAX_LENGTH).to_c_str();
let result = unsafe { gethostname(name.as_mut_ptr(), HOSTNAME_MAX_LENGTH as size_t) };
if result == 0 {
Ok(name.to_string())
} else {
Err("Failed to get hostname".to_string())
}
}
fn println(message: String) {
println!("{}", message);
}
fn err_println(message: String) {
let result = stdio::stderr().write(message.as_bytes());
match result {
Ok(_) => (),
Err(failure) => fail!(format!("Failed to write to stderr: {}", failure))
}
}
| get_hostname | identifier_name |
hostname.rs | extern crate getopts;
extern crate libc;
use getopts::{optflag, getopts, usage, OptGroup};
use libc::{c_char, c_int, size_t};
use std::io::stdio;
use std::os;
static HOSTNAME_MAX_LENGTH: uint = 256;
extern {
fn gethostname(name: *mut c_char, namelen: size_t) -> c_int;
}
fn main() {
let exit_status = run(os::args());
os::set_exit_status(exit_status);
}
fn usage_message(program: &String, options: &[OptGroup]) -> String |
fn run(args: Vec<String>) -> int {
let program = &args[0];
let parameters = [
optflag("V", "version", "Print the version number and exit"),
optflag("h", "help", "Print this help message")
];
let options = match getopts(args.tail(), parameters) {
Ok(options) => options,
Err(failure) => fail!(failure.to_string())
};
if options.opt_present("h") {
println(usage_message(program, parameters));
return 0;
}
if options.opt_present("V") {
println!("hostname 1.0.0");
return 0;
}
if options.free.len() == 1 {
err_println("hostname: you must be root to change the host name\n".to_string());
return 1;
}
match get_hostname() {
Ok(hostname) => println(hostname),
Err(error) => err_println(error)
}
return 0;
}
fn get_hostname() -> Result<String, String> {
let mut name = String::with_capacity(HOSTNAME_MAX_LENGTH).to_c_str();
let result = unsafe { gethostname(name.as_mut_ptr(), HOSTNAME_MAX_LENGTH as size_t) };
if result == 0 {
Ok(name.to_string())
} else {
Err("Failed to get hostname".to_string())
}
}
fn println(message: String) {
println!("{}", message);
}
fn err_println(message: String) {
let result = stdio::stderr().write(message.as_bytes());
match result {
Ok(_) => (),
Err(failure) => fail!(format!("Failed to write to stderr: {}", failure))
}
}
| {
let instructions = format!("Usage: {} [options] [HOSTNAME]", program);
usage(instructions.as_slice(), options)
} | identifier_body |
hostname.rs | extern crate getopts;
extern crate libc;
use getopts::{optflag, getopts, usage, OptGroup};
use libc::{c_char, c_int, size_t};
use std::io::stdio;
use std::os;
static HOSTNAME_MAX_LENGTH: uint = 256;
extern {
fn gethostname(name: *mut c_char, namelen: size_t) -> c_int; | os::set_exit_status(exit_status);
}
fn usage_message(program: &String, options: &[OptGroup]) -> String {
let instructions = format!("Usage: {} [options] [HOSTNAME]", program);
usage(instructions.as_slice(), options)
}
fn run(args: Vec<String>) -> int {
let program = &args[0];
let parameters = [
optflag("V", "version", "Print the version number and exit"),
optflag("h", "help", "Print this help message")
];
let options = match getopts(args.tail(), parameters) {
Ok(options) => options,
Err(failure) => fail!(failure.to_string())
};
if options.opt_present("h") {
println(usage_message(program, parameters));
return 0;
}
if options.opt_present("V") {
println!("hostname 1.0.0");
return 0;
}
if options.free.len() == 1 {
err_println("hostname: you must be root to change the host name\n".to_string());
return 1;
}
match get_hostname() {
Ok(hostname) => println(hostname),
Err(error) => err_println(error)
}
return 0;
}
fn get_hostname() -> Result<String, String> {
let mut name = String::with_capacity(HOSTNAME_MAX_LENGTH).to_c_str();
let result = unsafe { gethostname(name.as_mut_ptr(), HOSTNAME_MAX_LENGTH as size_t) };
if result == 0 {
Ok(name.to_string())
} else {
Err("Failed to get hostname".to_string())
}
}
fn println(message: String) {
println!("{}", message);
}
fn err_println(message: String) {
let result = stdio::stderr().write(message.as_bytes());
match result {
Ok(_) => (),
Err(failure) => fail!(format!("Failed to write to stderr: {}", failure))
}
} | }
fn main() {
let exit_status = run(os::args()); | random_line_split |
lib.rs | //! If you want to render templates, see the [`Render`](trait.Render.html)
//! trait.
//!
//! To customise the templating behavior, see the
//! [`TemplateSupport`](trait.TemplateSupport.html) trait.
#![deny(missing_docs)]
#[macro_use]
extern crate nickel;
extern crate mustache;
extern crate rustc_serialize;
use rustc_serialize::Encodable;
use mustache::{Data, Template};
use std::borrow::Cow;
use std::path::Path;
mod default_implementations;
mod response_extension;
/// Extension trait for common `mustache::Template` usage.
pub trait Render {
/// Return type for all of the extension methods.
type Output;
/// Renders a `mustache::Template` with specific `Encodable` data
///
/// See `examples/example.rs` for example usage.
fn render<T, P>(self, path: P, data: &T) -> Self::Output
where T: Encodable,
P: AsRef<Path>;
/// Renders a `mustache::Template` wrapped inside a specific layout
///
/// See `examples/with_layout.rs` for example usage.
fn render_with_layout<T, P, L>(self, path: P, layout: L, data: &T) -> Self::Output
where T: Encodable,
P: AsRef<Path>,
L: AsRef<Path>;
/// Renders a `mustache::Template` with specific `mustache::Data`
///
/// See `examples/helper_functions.rs` for example usage.
fn render_data<P>(self, path: P, data: &Data) -> Self::Output where P: AsRef<Path>;
/// Renders a `mustache::Template` wrapped inside a specific layout
///
/// See `examples/with_layout.rs` for example usage.
fn render_data_with_layout<P, L>(self, path: P, layout: L, data: &Data) -> Self::Output
where P: AsRef<Path>,
L: AsRef<Path>;
}
/// Customise the behaviour of the templating system.
pub trait TemplateSupport {
/// What type to dispatch the cache handling to.
///
/// # Note
///
/// Currently if you don't want custom behavior you should use `()` as your
/// `Cache`. When 'associated type defaults' becomes stable then this won't
/// be necessary to specify anymore.
type Cache: TemplateCache;
/// A reference to the `Cache` if there is one.
fn cache(&self) -> Option<&Self::Cache> { | ///
/// This can be useful if you want to keep a clean directory structure
/// without having to spread that knowledge across your handlers.
///
/// See `examples/adjusted_path.rs` for example usage.
fn adjust_path<'a>(&self, path: &'a Path) -> Cow<'a, Path> {
Cow::Borrowed(path)
}
/// Adjust the path of a layout lookup before it gets compiled.
///
/// This can be useful if you want to keep a clean directory structure
/// without having to spread that knowledge across your handlers.
///
/// See `examples/adjusted_path.rs` for example usage.
fn adjust_layout_path<'a>(&self, path: &'a Path) -> Cow<'a, Path> {
Cow::Borrowed(path)
}
/// The default layout to use when rendering.
///
/// See `examples/default_layout.rs` for example usage.
fn default_layout(&self) -> Option<Cow<Path>> {
None
}
}
/// Handle template caching through a borrowed reference.
pub trait TemplateCache {
/// Handles a cache lookup for a given template.
///
/// # Expected behavior
/// ```not_rust
/// if let Some(template) = cache.get(path) {
/// return handle(template)
/// } else {
/// let template = on_miss(path);
/// return handle(template)
/// }
/// ```
///
/// # Fix-me!
/// The signature is a bit crazy, but due to the nature of the interior mutability
/// required it's difficult to express a general interface without restrictions
/// on the kinds of type `TemplateCache` could be implemented for.
///
/// Any improvements to get it to a more `entry`-like design are welcome!
fn handle<'a, P, F, R>(&self, path: &'a Path, handle: P, on_miss: F) -> R
where P: FnOnce(Result<&Template, CompileError>) -> R,
F: FnOnce(&'a Path) -> Result<Template, CompileError>;
}
/// Currently the errors are `String`s
pub type CompileError = String; | None
}
/// Adjust the path of a template lookup before it gets compiled. | random_line_split |
lib.rs | //! If you want to render templates, see the [`Render`](trait.Render.html)
//! trait.
//!
//! To customise the templating behavior, see the
//! [`TemplateSupport`](trait.TemplateSupport.html) trait.
#![deny(missing_docs)]
#[macro_use]
extern crate nickel;
extern crate mustache;
extern crate rustc_serialize;
use rustc_serialize::Encodable;
use mustache::{Data, Template};
use std::borrow::Cow;
use std::path::Path;
mod default_implementations;
mod response_extension;
/// Extension trait for common `mustache::Template` usage.
pub trait Render {
/// Return type for all of the extension methods.
type Output;
/// Renders a `mustache::Template` with specific `Encodable` data
///
/// See `examples/example.rs` for example usage.
fn render<T, P>(self, path: P, data: &T) -> Self::Output
where T: Encodable,
P: AsRef<Path>;
/// Renders a `mustache::Template` wrapped inside a specific layout
///
/// See `examples/with_layout.rs` for example usage.
fn render_with_layout<T, P, L>(self, path: P, layout: L, data: &T) -> Self::Output
where T: Encodable,
P: AsRef<Path>,
L: AsRef<Path>;
/// Renders a `mustache::Template` with specific `mustache::Data`
///
/// See `examples/helper_functions.rs` for example usage.
fn render_data<P>(self, path: P, data: &Data) -> Self::Output where P: AsRef<Path>;
/// Renders a `mustache::Template` wrapped inside a specific layout
///
/// See `examples/with_layout.rs` for example usage.
fn render_data_with_layout<P, L>(self, path: P, layout: L, data: &Data) -> Self::Output
where P: AsRef<Path>,
L: AsRef<Path>;
}
/// Customise the behaviour of the templating system.
pub trait TemplateSupport {
/// What type to dispatch the cache handling to.
///
/// # Note
///
/// Currently if you don't want custom behavior you should use `()` as your
/// `Cache`. When 'associated type defaults' becomes stable then this won't
/// be necessary to specify anymore.
type Cache: TemplateCache;
/// A reference to the `Cache` if there is one.
fn cache(&self) -> Option<&Self::Cache> {
None
}
/// Adjust the path of a template lookup before it gets compiled.
///
/// This can be useful if you want to keep a clean directory structure
/// without having to spread that knowledge across your handlers.
///
/// See `examples/adjusted_path.rs` for example usage.
fn adjust_path<'a>(&self, path: &'a Path) -> Cow<'a, Path> {
Cow::Borrowed(path)
}
/// Adjust the path of a layout lookup before it gets compiled.
///
/// This can be useful if you want to keep a clean directory structure
/// without having to spread that knowledge across your handlers.
///
/// See `examples/adjusted_path.rs` for example usage.
fn | <'a>(&self, path: &'a Path) -> Cow<'a, Path> {
Cow::Borrowed(path)
}
/// The default layout to use when rendering.
///
/// See `examples/default_layout.rs` for example usage.
fn default_layout(&self) -> Option<Cow<Path>> {
None
}
}
/// Handle template caching through a borrowed reference.
pub trait TemplateCache {
/// Handles a cache lookup for a given template.
///
/// # Expected behavior
/// ```not_rust
/// if let Some(template) = cache.get(path) {
/// return handle(template)
/// } else {
/// let template = on_miss(path);
/// return handle(template)
/// }
/// ```
///
/// # Fix-me!
/// The signature is a bit crazy, but due to the nature of the interior mutability
/// required it's difficult to express a general interface without restrictions
/// on the kinds of type `TemplateCache` could be implemented for.
///
/// Any improvements to get it to a more `entry`-like design are welcome!
fn handle<'a, P, F, R>(&self, path: &'a Path, handle: P, on_miss: F) -> R
where P: FnOnce(Result<&Template, CompileError>) -> R,
F: FnOnce(&'a Path) -> Result<Template, CompileError>;
}
/// Currently the errors are `String`s
pub type CompileError = String;
| adjust_layout_path | identifier_name |
lib.rs | //! If you want to render templates, see the [`Render`](trait.Render.html)
//! trait.
//!
//! To customise the templating behavior, see the
//! [`TemplateSupport`](trait.TemplateSupport.html) trait.
#![deny(missing_docs)]
#[macro_use]
extern crate nickel;
extern crate mustache;
extern crate rustc_serialize;
use rustc_serialize::Encodable;
use mustache::{Data, Template};
use std::borrow::Cow;
use std::path::Path;
mod default_implementations;
mod response_extension;
/// Extension trait for common `mustache::Template` usage.
pub trait Render {
/// Return type for all of the extension methods.
type Output;
/// Renders a `mustache::Template` with specific `Encodable` data
///
/// See `examples/example.rs` for example usage.
fn render<T, P>(self, path: P, data: &T) -> Self::Output
where T: Encodable,
P: AsRef<Path>;
/// Renders a `mustache::Template` wrapped inside a specific layout
///
/// See `examples/with_layout.rs` for example usage.
fn render_with_layout<T, P, L>(self, path: P, layout: L, data: &T) -> Self::Output
where T: Encodable,
P: AsRef<Path>,
L: AsRef<Path>;
/// Renders a `mustache::Template` with specific `mustache::Data`
///
/// See `examples/helper_functions.rs` for example usage.
fn render_data<P>(self, path: P, data: &Data) -> Self::Output where P: AsRef<Path>;
/// Renders a `mustache::Template` wrapped inside a specific layout
///
/// See `examples/with_layout.rs` for example usage.
fn render_data_with_layout<P, L>(self, path: P, layout: L, data: &Data) -> Self::Output
where P: AsRef<Path>,
L: AsRef<Path>;
}
/// Customise the behaviour of the templating system.
pub trait TemplateSupport {
/// What type to dispatch the cache handling to.
///
/// # Note
///
/// Currently if you don't want custom behavior you should use `()` as your
/// `Cache`. When 'associated type defaults' becomes stable then this won't
/// be necessary to specify anymore.
type Cache: TemplateCache;
/// A reference to the `Cache` if there is one.
fn cache(&self) -> Option<&Self::Cache> {
None
}
/// Adjust the path of a template lookup before it gets compiled.
///
/// This can be useful if you want to keep a clean directory structure
/// without having to spread that knowledge across your handlers.
///
/// See `examples/adjusted_path.rs` for example usage.
fn adjust_path<'a>(&self, path: &'a Path) -> Cow<'a, Path> {
Cow::Borrowed(path)
}
/// Adjust the path of a layout lookup before it gets compiled.
///
/// This can be useful if you want to keep a clean directory structure
/// without having to spread that knowledge across your handlers.
///
/// See `examples/adjusted_path.rs` for example usage.
fn adjust_layout_path<'a>(&self, path: &'a Path) -> Cow<'a, Path> {
Cow::Borrowed(path)
}
/// The default layout to use when rendering.
///
/// See `examples/default_layout.rs` for example usage.
fn default_layout(&self) -> Option<Cow<Path>> |
}
/// Handle template caching through a borrowed reference.
pub trait TemplateCache {
/// Handles a cache lookup for a given template.
///
/// # Expected behavior
/// ```not_rust
/// if let Some(template) = cache.get(path) {
/// return handle(template)
/// } else {
/// let template = on_miss(path);
/// return handle(template)
/// }
/// ```
///
/// # Fix-me!
/// The signature is a bit crazy, but due to the nature of the interior mutability
/// required it's difficult to express a general interface without restrictions
/// on the kinds of type `TemplateCache` could be implemented for.
///
/// Any improvements to get it to a more `entry`-like design are welcome!
fn handle<'a, P, F, R>(&self, path: &'a Path, handle: P, on_miss: F) -> R
where P: FnOnce(Result<&Template, CompileError>) -> R,
F: FnOnce(&'a Path) -> Result<Template, CompileError>;
}
/// Currently the errors are `String`s
pub type CompileError = String;
| {
None
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.