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 |
---|---|---|---|---|
ac97_mixer.rs
|
// Copyright 2018 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use crate::pci::ac97_regs::*;
// AC97 Vendor ID
const AC97_VENDOR_ID1: u16 = 0x8086;
const AC97_VENDOR_ID2: u16 = 0x8086;
// Extented Audio ID
const AC97_EXTENDED_ID: u16 = MIXER_EI_VRA | MIXER_EI_CDAC | MIXER_EI_SDAC | MIXER_EI_LDAC;
// Master volume register is specified in 1.5dB steps.
const MASTER_VOLUME_STEP_DB: f64 = 1.5;
/// `Ac97Mixer` holds the mixer state for the AC97 bus.
/// The mixer is used by calling the `readb`/`readw`/`readl` functions to read register values and
/// the `writeb`/`writew`/`writel` functions to set register values.
pub struct Ac97Mixer {
// Mixer Registers
master_volume_l: u8,
master_volume_r: u8,
master_mute: bool,
mic_muted: bool,
mic_20db: bool,
mic_volume: u8,
record_gain_l: u8,
record_gain_r: u8,
record_gain_mute: bool,
pcm_out_vol_l: u16,
pcm_out_vol_r: u16,
pcm_out_mute: bool,
power_down_control: u16,
ext_audio_status_ctl: u16,
pcm_front_dac_rate: u16,
pcm_surr_dac_rate: u16,
pcm_lfe_dac_rate: u16,
}
impl Ac97Mixer {
/// Creates an 'Ac97Mixer' with the standard default register values.
pub fn new() -> Self {
Ac97Mixer {
master_volume_l: 0,
master_volume_r: 0,
master_mute: true,
mic_muted: true,
mic_20db: false,
mic_volume: 0x8,
record_gain_l: 0,
record_gain_r: 0,
record_gain_mute: true,
pcm_out_vol_l: 0x8,
pcm_out_vol_r: 0x8,
pcm_out_mute: true,
power_down_control: PD_REG_STATUS_MASK, // Report everything is ready.
ext_audio_status_ctl: 0,
// Default to 48 kHz.
pcm_front_dac_rate: 0xBB80,
pcm_surr_dac_rate: 0xBB80,
pcm_lfe_dac_rate: 0xBB80,
}
}
pub fn reset(&mut self) {
// Upon reset, the audio sample rate registers default to 48 kHz, and VRA=0.
self.ext_audio_status_ctl &=!MIXER_EI_VRA;
self.pcm_front_dac_rate = 0xBB80;
self.pcm_surr_dac_rate = 0xBB80;
self.pcm_lfe_dac_rate = 0xBB80;
}
/// Reads a word from the register at `offset`.
pub fn readw(&self, offset: u64) -> u16 {
match offset {
MIXER_RESET_00 => BC_DEDICATED_MIC,
MIXER_MASTER_VOL_MUTE_02 => self.get_master_reg(),
MIXER_MIC_VOL_MUTE_0E => self.get_mic_volume(),
MIXER_PCM_OUT_VOL_MUTE_18 => self.get_pcm_out_volume(),
MIXER_REC_VOL_MUTE_1C => self.get_record_gain_reg(),
MIXER_POWER_DOWN_CONTROL_26 => self.power_down_control,
MIXER_EXTENDED_AUDIO_ID_28 => AC97_EXTENDED_ID,
MIXER_VENDOR_ID1_7C => AC97_VENDOR_ID1,
MIXER_VENDOR_ID2_7E => AC97_VENDOR_ID2,
MIXER_EXTENDED_AUDIO_STATUS_CONTROL_28 => self.ext_audio_status_ctl,
MIXER_PCM_FRONT_DAC_RATE_2C => self.pcm_front_dac_rate,
MIXER_PCM_SURR_DAC_RATE_2E => self.pcm_surr_dac_rate,
MIXER_PCM_LFE_DAC_RATE_30 => self.pcm_lfe_dac_rate,
_ => 0,
}
}
/// Writes a word `val` to the register `offset`.
pub fn
|
(&mut self, offset: u64, val: u16) {
match offset {
MIXER_RESET_00 => self.reset(),
MIXER_MASTER_VOL_MUTE_02 => self.set_master_reg(val),
MIXER_MIC_VOL_MUTE_0E => self.set_mic_volume(val),
MIXER_PCM_OUT_VOL_MUTE_18 => self.set_pcm_out_volume(val),
MIXER_REC_VOL_MUTE_1C => self.set_record_gain_reg(val),
MIXER_POWER_DOWN_CONTROL_26 => self.set_power_down_reg(val),
MIXER_EXTENDED_AUDIO_STATUS_CONTROL_28 => self.ext_audio_status_ctl = val,
MIXER_PCM_FRONT_DAC_RATE_2C => self.pcm_front_dac_rate = val,
MIXER_PCM_SURR_DAC_RATE_2E => self.pcm_surr_dac_rate = val,
MIXER_PCM_LFE_DAC_RATE_30 => self.pcm_lfe_dac_rate = val,
_ => (),
}
}
/// Returns the mute status and left and right attenuation from the master volume register.
pub fn get_master_volume(&self) -> (bool, f64, f64) {
(
self.master_mute,
f64::from(self.master_volume_l) * MASTER_VOLUME_STEP_DB,
f64::from(self.master_volume_r) * MASTER_VOLUME_STEP_DB,
)
}
/// Returns the front sample rate (reg 0x2c).
pub fn get_sample_rate(&self) -> u16 {
// MIXER_PCM_FRONT_DAC_RATE_2C, MIXER_PCM_SURR_DAC_RATE_2E, and MIXER_PCM_LFE_DAC_RATE_30
// are updated to the same rate when playback with 2,4 and 6 tubes.
self.pcm_front_dac_rate
}
// Returns the master mute and l/r volumes (reg 0x02).
fn get_master_reg(&self) -> u16 {
let reg = (u16::from(self.master_volume_l)) << 8 | u16::from(self.master_volume_r);
if self.master_mute {
reg | MUTE_REG_BIT
} else {
reg
}
}
// Handles writes to the master register (0x02).
fn set_master_reg(&mut self, val: u16) {
self.master_mute = val & MUTE_REG_BIT!= 0;
self.master_volume_r = (val & VOL_REG_MASK) as u8;
self.master_volume_l = (val >> 8 & VOL_REG_MASK) as u8;
}
// Returns the value read in the Mic volume register (0x0e).
fn get_mic_volume(&self) -> u16 {
let mut reg = u16::from(self.mic_volume);
if self.mic_muted {
reg |= MUTE_REG_BIT;
}
if self.mic_20db {
reg |= MIXER_MIC_20DB;
}
reg
}
// Sets the mic input mute, boost, and volume settings (0x0e).
fn set_mic_volume(&mut self, val: u16) {
self.mic_volume = (val & MIXER_VOL_MASK) as u8;
self.mic_muted = val & MUTE_REG_BIT!= 0;
self.mic_20db = val & MIXER_MIC_20DB!= 0;
}
// Returns the value read in the Mic volume register (0x18).
fn get_pcm_out_volume(&self) -> u16 {
let reg = (self.pcm_out_vol_l as u16) << 8 | self.pcm_out_vol_r as u16;
if self.pcm_out_mute {
reg | MUTE_REG_BIT
} else {
reg
}
}
// Sets the pcm output mute and volume states (0x18).
fn set_pcm_out_volume(&mut self, val: u16) {
self.pcm_out_vol_r = val & MIXER_VOL_MASK;
self.pcm_out_vol_l = (val >> MIXER_VOL_LEFT_SHIFT) & MIXER_VOL_MASK;
self.pcm_out_mute = val & MUTE_REG_BIT!= 0;
}
// Returns the record gain register (0x01c).
fn get_record_gain_reg(&self) -> u16 {
let reg = u16::from(self.record_gain_l) << 8 | u16::from(self.record_gain_r);
if self.record_gain_mute {
reg | MUTE_REG_BIT
} else {
reg
}
}
// Handles writes to the record_gain register (0x1c).
fn set_record_gain_reg(&mut self, val: u16) {
self.record_gain_mute = val & MUTE_REG_BIT!= 0;
self.record_gain_r = (val & VOL_REG_MASK) as u8;
self.record_gain_l = (val >> 8 & VOL_REG_MASK) as u8;
}
// Handles writes to the powerdown ctrl/status register (0x26).
fn set_power_down_reg(&mut self, val: u16) {
self.power_down_control =
(val &!PD_REG_STATUS_MASK) | (self.power_down_control & PD_REG_STATUS_MASK);
}
}
|
writew
|
identifier_name
|
ac97_mixer.rs
|
// Copyright 2018 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use crate::pci::ac97_regs::*;
// AC97 Vendor ID
const AC97_VENDOR_ID1: u16 = 0x8086;
const AC97_VENDOR_ID2: u16 = 0x8086;
// Extented Audio ID
const AC97_EXTENDED_ID: u16 = MIXER_EI_VRA | MIXER_EI_CDAC | MIXER_EI_SDAC | MIXER_EI_LDAC;
// Master volume register is specified in 1.5dB steps.
const MASTER_VOLUME_STEP_DB: f64 = 1.5;
/// `Ac97Mixer` holds the mixer state for the AC97 bus.
/// The mixer is used by calling the `readb`/`readw`/`readl` functions to read register values and
/// the `writeb`/`writew`/`writel` functions to set register values.
pub struct Ac97Mixer {
// Mixer Registers
master_volume_l: u8,
master_volume_r: u8,
master_mute: bool,
mic_muted: bool,
mic_20db: bool,
mic_volume: u8,
record_gain_l: u8,
record_gain_r: u8,
record_gain_mute: bool,
pcm_out_vol_l: u16,
pcm_out_vol_r: u16,
pcm_out_mute: bool,
power_down_control: u16,
ext_audio_status_ctl: u16,
pcm_front_dac_rate: u16,
pcm_surr_dac_rate: u16,
pcm_lfe_dac_rate: u16,
}
impl Ac97Mixer {
/// Creates an 'Ac97Mixer' with the standard default register values.
pub fn new() -> Self {
Ac97Mixer {
master_volume_l: 0,
master_volume_r: 0,
master_mute: true,
mic_muted: true,
mic_20db: false,
mic_volume: 0x8,
record_gain_l: 0,
record_gain_r: 0,
record_gain_mute: true,
pcm_out_vol_l: 0x8,
pcm_out_vol_r: 0x8,
pcm_out_mute: true,
power_down_control: PD_REG_STATUS_MASK, // Report everything is ready.
ext_audio_status_ctl: 0,
// Default to 48 kHz.
pcm_front_dac_rate: 0xBB80,
pcm_surr_dac_rate: 0xBB80,
pcm_lfe_dac_rate: 0xBB80,
}
}
pub fn reset(&mut self) {
// Upon reset, the audio sample rate registers default to 48 kHz, and VRA=0.
self.ext_audio_status_ctl &=!MIXER_EI_VRA;
self.pcm_front_dac_rate = 0xBB80;
self.pcm_surr_dac_rate = 0xBB80;
self.pcm_lfe_dac_rate = 0xBB80;
}
/// Reads a word from the register at `offset`.
pub fn readw(&self, offset: u64) -> u16 {
match offset {
MIXER_RESET_00 => BC_DEDICATED_MIC,
MIXER_MASTER_VOL_MUTE_02 => self.get_master_reg(),
MIXER_MIC_VOL_MUTE_0E => self.get_mic_volume(),
MIXER_PCM_OUT_VOL_MUTE_18 => self.get_pcm_out_volume(),
MIXER_REC_VOL_MUTE_1C => self.get_record_gain_reg(),
MIXER_POWER_DOWN_CONTROL_26 => self.power_down_control,
MIXER_EXTENDED_AUDIO_ID_28 => AC97_EXTENDED_ID,
MIXER_VENDOR_ID1_7C => AC97_VENDOR_ID1,
MIXER_VENDOR_ID2_7E => AC97_VENDOR_ID2,
MIXER_EXTENDED_AUDIO_STATUS_CONTROL_28 => self.ext_audio_status_ctl,
MIXER_PCM_FRONT_DAC_RATE_2C => self.pcm_front_dac_rate,
MIXER_PCM_SURR_DAC_RATE_2E => self.pcm_surr_dac_rate,
MIXER_PCM_LFE_DAC_RATE_30 => self.pcm_lfe_dac_rate,
_ => 0,
}
}
/// Writes a word `val` to the register `offset`.
pub fn writew(&mut self, offset: u64, val: u16) {
match offset {
MIXER_RESET_00 => self.reset(),
MIXER_MASTER_VOL_MUTE_02 => self.set_master_reg(val),
MIXER_MIC_VOL_MUTE_0E => self.set_mic_volume(val),
MIXER_PCM_OUT_VOL_MUTE_18 => self.set_pcm_out_volume(val),
MIXER_REC_VOL_MUTE_1C => self.set_record_gain_reg(val),
MIXER_POWER_DOWN_CONTROL_26 => self.set_power_down_reg(val),
MIXER_EXTENDED_AUDIO_STATUS_CONTROL_28 => self.ext_audio_status_ctl = val,
MIXER_PCM_FRONT_DAC_RATE_2C => self.pcm_front_dac_rate = val,
MIXER_PCM_SURR_DAC_RATE_2E => self.pcm_surr_dac_rate = val,
MIXER_PCM_LFE_DAC_RATE_30 => self.pcm_lfe_dac_rate = val,
_ => (),
}
}
/// Returns the mute status and left and right attenuation from the master volume register.
pub fn get_master_volume(&self) -> (bool, f64, f64) {
(
self.master_mute,
f64::from(self.master_volume_l) * MASTER_VOLUME_STEP_DB,
f64::from(self.master_volume_r) * MASTER_VOLUME_STEP_DB,
)
}
/// Returns the front sample rate (reg 0x2c).
pub fn get_sample_rate(&self) -> u16 {
// MIXER_PCM_FRONT_DAC_RATE_2C, MIXER_PCM_SURR_DAC_RATE_2E, and MIXER_PCM_LFE_DAC_RATE_30
// are updated to the same rate when playback with 2,4 and 6 tubes.
self.pcm_front_dac_rate
}
// Returns the master mute and l/r volumes (reg 0x02).
fn get_master_reg(&self) -> u16 {
let reg = (u16::from(self.master_volume_l)) << 8 | u16::from(self.master_volume_r);
if self.master_mute {
reg | MUTE_REG_BIT
} else {
reg
}
}
// Handles writes to the master register (0x02).
fn set_master_reg(&mut self, val: u16) {
self.master_mute = val & MUTE_REG_BIT!= 0;
self.master_volume_r = (val & VOL_REG_MASK) as u8;
self.master_volume_l = (val >> 8 & VOL_REG_MASK) as u8;
}
// Returns the value read in the Mic volume register (0x0e).
fn get_mic_volume(&self) -> u16
|
// Sets the mic input mute, boost, and volume settings (0x0e).
fn set_mic_volume(&mut self, val: u16) {
self.mic_volume = (val & MIXER_VOL_MASK) as u8;
self.mic_muted = val & MUTE_REG_BIT!= 0;
self.mic_20db = val & MIXER_MIC_20DB!= 0;
}
// Returns the value read in the Mic volume register (0x18).
fn get_pcm_out_volume(&self) -> u16 {
let reg = (self.pcm_out_vol_l as u16) << 8 | self.pcm_out_vol_r as u16;
if self.pcm_out_mute {
reg | MUTE_REG_BIT
} else {
reg
}
}
// Sets the pcm output mute and volume states (0x18).
fn set_pcm_out_volume(&mut self, val: u16) {
self.pcm_out_vol_r = val & MIXER_VOL_MASK;
self.pcm_out_vol_l = (val >> MIXER_VOL_LEFT_SHIFT) & MIXER_VOL_MASK;
self.pcm_out_mute = val & MUTE_REG_BIT!= 0;
}
// Returns the record gain register (0x01c).
fn get_record_gain_reg(&self) -> u16 {
let reg = u16::from(self.record_gain_l) << 8 | u16::from(self.record_gain_r);
if self.record_gain_mute {
reg | MUTE_REG_BIT
} else {
reg
}
}
// Handles writes to the record_gain register (0x1c).
fn set_record_gain_reg(&mut self, val: u16) {
self.record_gain_mute = val & MUTE_REG_BIT!= 0;
self.record_gain_r = (val & VOL_REG_MASK) as u8;
self.record_gain_l = (val >> 8 & VOL_REG_MASK) as u8;
}
// Handles writes to the powerdown ctrl/status register (0x26).
fn set_power_down_reg(&mut self, val: u16) {
self.power_down_control =
(val &!PD_REG_STATUS_MASK) | (self.power_down_control & PD_REG_STATUS_MASK);
}
}
|
{
let mut reg = u16::from(self.mic_volume);
if self.mic_muted {
reg |= MUTE_REG_BIT;
}
if self.mic_20db {
reg |= MIXER_MIC_20DB;
}
reg
}
|
identifier_body
|
homebrew.rs
|
// Copyright 2015-2017 Intecture Developers.
//
// Licensed under the Mozilla Public License 2.0 <LICENSE or
// https://www.tldrlegal.com/l/mpl-2.0>. This file may not be copied,
// modified, or distributed except according to those terms.
use command::Child;
use error_chain::ChainedError;
use errors::*;
use futures::{future, Future};
use futures::future::FutureResult;
use host::local::Local;
use std::process;
use super::{Launchctl, ServiceProvider};
use telemetry::Telemetry;
pub struct Homebrew {
inner: Launchctl,
}
impl Homebrew {
#[doc(hidden)]
pub fn new(telemetry: &Telemetry) -> Homebrew {
Homebrew {
inner: Launchctl::new(telemetry),
}
}
}
impl ServiceProvider for Homebrew {
fn available(telemetry: &Telemetry) -> Result<bool> {
let brew = process::Command::new("/usr/bin/type")
.arg("brew")
.status()
.chain_err(|| "Could not determine provider availability")?
.success();
Ok(brew && Launchctl::available(telemetry)?)
}
fn running(&self, host: &Local, name: &str) -> Box<Future<Item = bool, Error = Error>> {
self.inner.running(host, name)
}
fn action(&self, host: &Local, name: &str, action: &str) -> FutureResult<Child, Error> {
// @todo This isn't the most reliable method. Ideally a user would
// invoke these commands themselves.
let result = if action == "stop" {
self.inner.uninstall_plist(name)
} else {
let path = format!("/usr/local/opt/{}/homebrew.mxcl.{0}.plist", name);
self.inner.install_plist(path)
};
match result {
Ok(_) => self.inner.action(host, name, action),
Err(e) => future::err(format!("{}", e.display_chain()).into())
}
}
fn enabled(&self, host: &Local, name: &str) -> Box<Future<Item = bool, Error = Error>> {
self.inner.enabled(host, name)
}
fn
|
(&self, host: &Local, name: &str) -> Box<Future<Item = (), Error = Error>> {
self.inner.enable(host, name)
}
fn disable(&self, host: &Local, name: &str) -> Box<Future<Item = (), Error = Error>> {
self.inner.disable(host, name)
}
}
|
enable
|
identifier_name
|
homebrew.rs
|
// Copyright 2015-2017 Intecture Developers.
//
// Licensed under the Mozilla Public License 2.0 <LICENSE or
// https://www.tldrlegal.com/l/mpl-2.0>. This file may not be copied,
// modified, or distributed except according to those terms.
use command::Child;
use error_chain::ChainedError;
use errors::*;
use futures::{future, Future};
use futures::future::FutureResult;
use host::local::Local;
use std::process;
use super::{Launchctl, ServiceProvider};
use telemetry::Telemetry;
pub struct Homebrew {
inner: Launchctl,
}
impl Homebrew {
#[doc(hidden)]
pub fn new(telemetry: &Telemetry) -> Homebrew {
Homebrew {
inner: Launchctl::new(telemetry),
}
}
}
impl ServiceProvider for Homebrew {
fn available(telemetry: &Telemetry) -> Result<bool> {
let brew = process::Command::new("/usr/bin/type")
.arg("brew")
.status()
.chain_err(|| "Could not determine provider availability")?
.success();
Ok(brew && Launchctl::available(telemetry)?)
}
fn running(&self, host: &Local, name: &str) -> Box<Future<Item = bool, Error = Error>> {
self.inner.running(host, name)
}
fn action(&self, host: &Local, name: &str, action: &str) -> FutureResult<Child, Error> {
// @todo This isn't the most reliable method. Ideally a user would
// invoke these commands themselves.
|
let path = format!("/usr/local/opt/{}/homebrew.mxcl.{0}.plist", name);
self.inner.install_plist(path)
};
match result {
Ok(_) => self.inner.action(host, name, action),
Err(e) => future::err(format!("{}", e.display_chain()).into())
}
}
fn enabled(&self, host: &Local, name: &str) -> Box<Future<Item = bool, Error = Error>> {
self.inner.enabled(host, name)
}
fn enable(&self, host: &Local, name: &str) -> Box<Future<Item = (), Error = Error>> {
self.inner.enable(host, name)
}
fn disable(&self, host: &Local, name: &str) -> Box<Future<Item = (), Error = Error>> {
self.inner.disable(host, name)
}
}
|
let result = if action == "stop" {
self.inner.uninstall_plist(name)
} else {
|
random_line_split
|
homebrew.rs
|
// Copyright 2015-2017 Intecture Developers.
//
// Licensed under the Mozilla Public License 2.0 <LICENSE or
// https://www.tldrlegal.com/l/mpl-2.0>. This file may not be copied,
// modified, or distributed except according to those terms.
use command::Child;
use error_chain::ChainedError;
use errors::*;
use futures::{future, Future};
use futures::future::FutureResult;
use host::local::Local;
use std::process;
use super::{Launchctl, ServiceProvider};
use telemetry::Telemetry;
pub struct Homebrew {
inner: Launchctl,
}
impl Homebrew {
#[doc(hidden)]
pub fn new(telemetry: &Telemetry) -> Homebrew {
Homebrew {
inner: Launchctl::new(telemetry),
}
}
}
impl ServiceProvider for Homebrew {
fn available(telemetry: &Telemetry) -> Result<bool> {
let brew = process::Command::new("/usr/bin/type")
.arg("brew")
.status()
.chain_err(|| "Could not determine provider availability")?
.success();
Ok(brew && Launchctl::available(telemetry)?)
}
fn running(&self, host: &Local, name: &str) -> Box<Future<Item = bool, Error = Error>> {
self.inner.running(host, name)
}
fn action(&self, host: &Local, name: &str, action: &str) -> FutureResult<Child, Error> {
// @todo This isn't the most reliable method. Ideally a user would
// invoke these commands themselves.
let result = if action == "stop" {
self.inner.uninstall_plist(name)
} else {
let path = format!("/usr/local/opt/{}/homebrew.mxcl.{0}.plist", name);
self.inner.install_plist(path)
};
match result {
Ok(_) => self.inner.action(host, name, action),
Err(e) => future::err(format!("{}", e.display_chain()).into())
}
}
fn enabled(&self, host: &Local, name: &str) -> Box<Future<Item = bool, Error = Error>>
|
fn enable(&self, host: &Local, name: &str) -> Box<Future<Item = (), Error = Error>> {
self.inner.enable(host, name)
}
fn disable(&self, host: &Local, name: &str) -> Box<Future<Item = (), Error = Error>> {
self.inner.disable(host, name)
}
}
|
{
self.inner.enabled(host, name)
}
|
identifier_body
|
command.rs
|
// Copyright 2015 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#![allow(missing_docs)]
use gl;
use gfx_core as c;
use gfx_core::draw;
use gfx_core::state as s;
use gfx_core::target::{ColorValue, Depth, Mirror, Rect, Stencil};
use {Buffer, Program, FrameBuffer, Texture,
NewTexture, Resources, PipelineState, ResourceView, TargetView};
fn primitive_to_gl(primitive: c::Primitive) -> gl::types::GLenum {
use gfx_core::Primitive::*;
match primitive {
PointList => gl::POINTS,
LineList => gl::LINES,
LineStrip => gl::LINE_STRIP,
TriangleList => gl::TRIANGLES,
TriangleStrip => gl::TRIANGLE_STRIP,
//TriangleFan => gl::TRIANGLE_FAN,
}
}
pub type Access = gl::types::GLenum;
#[derive(Clone, Copy, Debug)]
pub struct RawOffset(pub *const gl::types::GLvoid);
unsafe impl Send for RawOffset {}
/// The place of some data in the data buffer.
#[derive(Clone, Copy, PartialEq, Debug)]
pub struct DataPointer {
offset: u32,
size: u32,
}
pub struct DataBuffer(Vec<u8>);
impl DataBuffer {
/// Create a new empty data buffer.
pub fn new() -> DataBuffer {
DataBuffer(Vec::new())
}
/// Copy a given vector slice into the buffer.
fn add(&mut self, data: &[u8]) -> DataPointer {
self.0.extend_from_slice(data);
DataPointer {
offset: (self.0.len() - data.len()) as u32,
size: data.len() as u32,
}
}
/// Return a reference to a stored data object.
pub fn get(&self, ptr: DataPointer) -> &[u8] {
&self.0[ptr.offset as usize.. (ptr.offset + ptr.size) as usize]
}
}
///Serialized device command.
#[derive(Clone, Copy, Debug)]
pub enum Command {
// states
BindProgram(Program),
BindConstantBuffer(c::pso::ConstantBufferParam<Resources>),
BindResourceView(c::pso::ResourceViewParam<Resources>),
BindUnorderedView(c::pso::UnorderedViewParam<Resources>),
BindSampler(c::pso::SamplerParam<Resources>, Option<gl::types::GLenum>),
BindPixelTargets(c::pso::PixelTargetSet<Resources>),
BindAttribute(c::AttributeSlot, Buffer, c::pso::AttributeDesc),
BindIndex(Buffer),
BindFrameBuffer(Access, FrameBuffer),
BindUniform(c::shade::Location, c::shade::UniformValue),
SetDrawColorBuffers(c::ColorSlot),
SetRasterizer(s::Rasterizer),
SetViewport(Rect),
SetScissor(Option<Rect>),
SetDepthState(Option<s::Depth>),
SetStencilState(Option<s::Stencil>, (Stencil, Stencil), s::CullFace),
SetBlendState(c::ColorSlot, s::Color),
SetBlendColor(ColorValue),
// resource updates
UpdateBuffer(Buffer, DataPointer, usize),
UpdateTexture(Texture, c::tex::Kind, Option<c::tex::CubeFace>,
DataPointer, c::tex::RawImageInfo),
GenerateMipmap(ResourceView),
// drawing
Clear(Option<draw::ClearColor>, Option<Depth>, Option<Stencil>),
Draw(gl::types::GLenum, c::VertexCount, c::VertexCount, draw::InstanceOption),
DrawIndexed(gl::types::GLenum, gl::types::GLenum, RawOffset,
c::VertexCount, c::VertexCount, draw::InstanceOption),
_Blit(Rect, Rect, Mirror, usize),
}
pub const COLOR_DEFAULT: s::Color = s::Color {
mask: s::MASK_ALL,
blend: None,
};
pub const RESET: [Command; 13] = [
Command::BindProgram(0),
// BindAttribute
Command::BindIndex(0),
Command::BindFrameBuffer(gl::FRAMEBUFFER, 0),
Command::SetRasterizer(s::Rasterizer {
front_face: s::FrontFace::CounterClockwise,
method: s::RasterMethod::Fill(s::CullFace::Back),
offset: None,
samples: None,
}),
Command::SetViewport(Rect{x: 0, y: 0, w: 0, h: 0}),
Command::SetScissor(None),
Command::SetDepthState(None),
Command::SetStencilState(None, (0, 0), s::CullFace::Nothing),
Command::SetBlendState(0, COLOR_DEFAULT),
Command::SetBlendState(1, COLOR_DEFAULT),
Command::SetBlendState(2, COLOR_DEFAULT),
Command::SetBlendState(3, COLOR_DEFAULT),
Command::SetBlendColor([0f32; 4]),
];
struct Cache {
primitive: gl::types::GLenum,
index_type: c::IndexType,
attributes: [Option<c::pso::AttributeDesc>; c::MAX_VERTEX_ATTRIBUTES],
resource_binds: [Option<gl::types::GLenum>; c::MAX_RESOURCE_VIEWS],
scissor: bool,
stencil: Option<s::Stencil>,
//blend: Option<s::Blend>,
cull_face: s::CullFace,
draw_mask: u32,
}
impl Cache {
pub fn new() -> Cache {
Cache {
primitive: 0,
index_type: c::IndexType::U8,
attributes: [None; c::MAX_VERTEX_ATTRIBUTES],
resource_binds: [None; c::MAX_RESOURCE_VIEWS],
scissor: false,
stencil: None,
cull_face: s::CullFace::Nothing,
//blend: None,
draw_mask: 0,
}
}
}
pub struct CommandBuffer {
pub buf: Vec<Command>,
pub data: DataBuffer,
fbo: FrameBuffer,
cache: Cache,
}
impl CommandBuffer {
pub fn new(fbo: FrameBuffer) -> CommandBuffer {
CommandBuffer {
buf: Vec::new(),
data: DataBuffer::new(),
fbo: fbo,
cache: Cache::new(),
}
}
fn is_main_target(&self, tv: Option<TargetView>) -> bool {
match tv {
Some(TargetView::Surface(0)) | None => true,
Some(_) => false,
}
}
}
impl c::draw::CommandBuffer<Resources> for CommandBuffer {
fn clone_empty(&self) -> CommandBuffer {
CommandBuffer::new(self.fbo)
}
fn reset(&mut self) {
self.buf.clear();
self.data.0.clear();
self.cache = Cache::new();
}
fn bind_pipeline_state(&mut self, pso: PipelineState) {
let cull = pso.rasterizer.method.get_cull_face();
self.cache.primitive = primitive_to_gl(pso.primitive);
self.cache.attributes = pso.input;
self.cache.stencil = pso.output.stencil;
self.cache.cull_face = cull;
self.cache.draw_mask = pso.output.draw_mask;
self.buf.push(Command::BindProgram(pso.program));
self.cache.scissor = pso.scissor;
self.buf.push(Command::SetRasterizer(pso.rasterizer));
self.buf.push(Command::SetDepthState(pso.output.depth));
self.buf.push(Command::SetStencilState(pso.output.stencil, (0, 0), cull));
for i in 0.. c::MAX_COLOR_TARGETS {
if pso.output.draw_mask & (1<<i)!= 0 {
self.buf.push(Command::SetBlendState(i as c::ColorSlot, pso.output.colors[i]));
}
}
}
fn bind_vertex_buffers(&mut self, vbs: c::pso::VertexBufferSet<Resources>) {
for i in 0.. c::MAX_VERTEX_ATTRIBUTES {
match (vbs.0[i], self.cache.attributes[i]) {
(None, Some(fm)) => {
error!("No vertex input provided for slot {} of format {:?}", i, fm)
},
(Some((buffer, offset)), Some(mut format)) => {
format.0.offset += offset as gl::types::GLuint;
self.buf.push(Command::BindAttribute(i as c::AttributeSlot, buffer, format));
},
(_, None) => (),
}
}
}
fn bind_constant_buffers(&mut self, cbs: &[c::pso::ConstantBufferParam<Resources>]) {
for param in cbs.iter() {
self.buf.push(Command::BindConstantBuffer(param.clone()));
}
}
fn bind_global_constant(&mut self, loc: c::shade::Location,
value: c::shade::UniformValue) {
self.buf.push(Command::BindUniform(loc, value));
}
fn bind_resource_views(&mut self, srvs: &[c::pso::ResourceViewParam<Resources>]) {
for i in 0.. c::MAX_RESOURCE_VIEWS {
self.cache.resource_binds[i] = None;
}
for param in srvs.iter() {
self.cache.resource_binds[param.2 as usize] = Some(param.0.bind);
self.buf.push(Command::BindResourceView(param.clone()));
}
}
fn bind_unordered_views(&mut self, uavs: &[c::pso::UnorderedViewParam<Resources>]) {
for param in uavs.iter() {
self.buf.push(Command::BindUnorderedView(param.clone()));
}
}
fn bind_samplers(&mut self, ss: &[c::pso::SamplerParam<Resources>]) {
for param in ss.iter() {
let bind = self.cache.resource_binds[param.2 as usize];
self.buf.push(Command::BindSampler(param.clone(), bind));
}
}
fn bind_pixel_targets(&mut self, pts: c::pso::PixelTargetSet<Resources>) {
let is_main = pts.colors.iter().skip(1).find(|c| c.is_some()).is_none() &&
self.is_main_target(pts.colors[0]) &&
self.is_main_target(pts.depth) &&
self.is_main_target(pts.stencil);
if is_main {
self.buf.push(Command::BindFrameBuffer(gl::DRAW_FRAMEBUFFER, 0));
}else {
let num = pts.colors.iter().position(|c| c.is_none())
.unwrap_or(pts.colors.len()) as c::ColorSlot;
self.buf.push(Command::BindFrameBuffer(gl::DRAW_FRAMEBUFFER, self.fbo));
self.buf.push(Command::BindPixelTargets(pts));
self.buf.push(Command::SetDrawColorBuffers(num));
}
self.buf.push(Command::SetViewport(Rect {
x: 0, y: 0, w: pts.size.0, h: pts.size.1}));
}
fn bind_index(&mut self, buf: Buffer, itype: c::IndexType) {
self.cache.index_type = itype;
self.buf.push(Command::BindIndex(buf));
}
fn set_scissor(&mut self, rect: Rect) {
self.buf.push(Command::SetScissor(
if self.cache.scissor {Some(rect)} else {None}
));
}
fn set_ref_values(&mut self, rv: s::RefValues) {
self.buf.push(Command::SetStencilState(self.cache.stencil, rv.stencil, self.cache.cull_face));
self.buf.push(Command::SetBlendColor(rv.blend));
}
fn update_buffer(&mut self, buf: Buffer, data: &[u8], offset_bytes: usize) {
let ptr = self.data.add(data);
self.buf.push(Command::UpdateBuffer(buf, ptr, offset_bytes));
}
fn update_texture(&mut self, ntex: NewTexture, kind: c::tex::Kind,
face: Option<c::tex::CubeFace>, data: &[u8],
img: c::tex::RawImageInfo) {
let ptr = self.data.add(data);
match ntex {
NewTexture::Texture(t) =>
self.buf.push(Command::UpdateTexture(t, kind, face, ptr, img)),
NewTexture::Surface(s) =>
error!("GL: unable to update the contents of a Surface({})", s),
}
}
fn generate_mipmap(&mut self, srv: ResourceView) {
self.buf.push(Command::GenerateMipmap(srv));
}
fn clear_color(&mut self, target: TargetView, value: draw::ClearColor) {
// this could be optimized by deferring the actual clear call
let mut pts = c::pso::PixelTargetSet::new();
pts.colors[0] = Some(target);
self.bind_pixel_targets(pts);
self.buf.push(Command::Clear(Some(value), None, None));
}
fn clear_depth_stencil(&mut self, target: TargetView, depth: Option<Depth>, stencil: Option<Stencil>) {
let mut pts = c::pso::PixelTargetSet::new();
if depth.is_some() {
pts.depth = Some(target);
}
if stencil.is_some() {
pts.stencil = Some(target);
}
self.bind_pixel_targets(pts);
self.buf.push(Command::Clear(None, depth, stencil));
}
fn
|
(&mut self, start: c::VertexCount,
count: c::VertexCount, instances: draw::InstanceOption) {
self.buf.push(Command::Draw(self.cache.primitive, start, count, instances));
}
fn call_draw_indexed(&mut self, start: c::VertexCount,
count: c::VertexCount, base: c::VertexCount,
instances: draw::InstanceOption) {
let (offset, gl_index) = match self.cache.index_type {
c::IndexType::U8 => (start * 1u32, gl::UNSIGNED_BYTE),
c::IndexType::U16 => (start * 2u32, gl::UNSIGNED_SHORT),
c::IndexType::U32 => (start * 4u32, gl::UNSIGNED_INT),
};
self.buf.push(Command::DrawIndexed(self.cache.primitive,
gl_index, RawOffset(offset as *const gl::types::GLvoid), count, base, instances));
}
}
|
call_draw
|
identifier_name
|
command.rs
|
// Copyright 2015 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#![allow(missing_docs)]
use gl;
use gfx_core as c;
use gfx_core::draw;
use gfx_core::state as s;
use gfx_core::target::{ColorValue, Depth, Mirror, Rect, Stencil};
use {Buffer, Program, FrameBuffer, Texture,
NewTexture, Resources, PipelineState, ResourceView, TargetView};
fn primitive_to_gl(primitive: c::Primitive) -> gl::types::GLenum {
use gfx_core::Primitive::*;
match primitive {
PointList => gl::POINTS,
LineList => gl::LINES,
LineStrip => gl::LINE_STRIP,
TriangleList => gl::TRIANGLES,
TriangleStrip => gl::TRIANGLE_STRIP,
//TriangleFan => gl::TRIANGLE_FAN,
}
}
pub type Access = gl::types::GLenum;
#[derive(Clone, Copy, Debug)]
pub struct RawOffset(pub *const gl::types::GLvoid);
unsafe impl Send for RawOffset {}
/// The place of some data in the data buffer.
#[derive(Clone, Copy, PartialEq, Debug)]
pub struct DataPointer {
offset: u32,
size: u32,
}
pub struct DataBuffer(Vec<u8>);
impl DataBuffer {
/// Create a new empty data buffer.
pub fn new() -> DataBuffer {
DataBuffer(Vec::new())
}
/// Copy a given vector slice into the buffer.
fn add(&mut self, data: &[u8]) -> DataPointer {
self.0.extend_from_slice(data);
DataPointer {
offset: (self.0.len() - data.len()) as u32,
size: data.len() as u32,
}
}
/// Return a reference to a stored data object.
pub fn get(&self, ptr: DataPointer) -> &[u8] {
&self.0[ptr.offset as usize.. (ptr.offset + ptr.size) as usize]
}
}
///Serialized device command.
#[derive(Clone, Copy, Debug)]
pub enum Command {
// states
BindProgram(Program),
BindConstantBuffer(c::pso::ConstantBufferParam<Resources>),
BindResourceView(c::pso::ResourceViewParam<Resources>),
BindUnorderedView(c::pso::UnorderedViewParam<Resources>),
BindSampler(c::pso::SamplerParam<Resources>, Option<gl::types::GLenum>),
BindPixelTargets(c::pso::PixelTargetSet<Resources>),
BindAttribute(c::AttributeSlot, Buffer, c::pso::AttributeDesc),
BindIndex(Buffer),
BindFrameBuffer(Access, FrameBuffer),
BindUniform(c::shade::Location, c::shade::UniformValue),
SetDrawColorBuffers(c::ColorSlot),
SetRasterizer(s::Rasterizer),
SetViewport(Rect),
SetScissor(Option<Rect>),
SetDepthState(Option<s::Depth>),
SetStencilState(Option<s::Stencil>, (Stencil, Stencil), s::CullFace),
SetBlendState(c::ColorSlot, s::Color),
SetBlendColor(ColorValue),
// resource updates
UpdateBuffer(Buffer, DataPointer, usize),
UpdateTexture(Texture, c::tex::Kind, Option<c::tex::CubeFace>,
DataPointer, c::tex::RawImageInfo),
GenerateMipmap(ResourceView),
// drawing
Clear(Option<draw::ClearColor>, Option<Depth>, Option<Stencil>),
Draw(gl::types::GLenum, c::VertexCount, c::VertexCount, draw::InstanceOption),
DrawIndexed(gl::types::GLenum, gl::types::GLenum, RawOffset,
c::VertexCount, c::VertexCount, draw::InstanceOption),
_Blit(Rect, Rect, Mirror, usize),
}
pub const COLOR_DEFAULT: s::Color = s::Color {
mask: s::MASK_ALL,
blend: None,
};
pub const RESET: [Command; 13] = [
Command::BindProgram(0),
// BindAttribute
Command::BindIndex(0),
Command::BindFrameBuffer(gl::FRAMEBUFFER, 0),
Command::SetRasterizer(s::Rasterizer {
front_face: s::FrontFace::CounterClockwise,
method: s::RasterMethod::Fill(s::CullFace::Back),
offset: None,
samples: None,
}),
Command::SetViewport(Rect{x: 0, y: 0, w: 0, h: 0}),
Command::SetScissor(None),
Command::SetDepthState(None),
Command::SetStencilState(None, (0, 0), s::CullFace::Nothing),
Command::SetBlendState(0, COLOR_DEFAULT),
Command::SetBlendState(1, COLOR_DEFAULT),
Command::SetBlendState(2, COLOR_DEFAULT),
Command::SetBlendState(3, COLOR_DEFAULT),
Command::SetBlendColor([0f32; 4]),
];
struct Cache {
primitive: gl::types::GLenum,
index_type: c::IndexType,
attributes: [Option<c::pso::AttributeDesc>; c::MAX_VERTEX_ATTRIBUTES],
resource_binds: [Option<gl::types::GLenum>; c::MAX_RESOURCE_VIEWS],
scissor: bool,
stencil: Option<s::Stencil>,
//blend: Option<s::Blend>,
cull_face: s::CullFace,
draw_mask: u32,
}
impl Cache {
pub fn new() -> Cache {
Cache {
primitive: 0,
index_type: c::IndexType::U8,
attributes: [None; c::MAX_VERTEX_ATTRIBUTES],
resource_binds: [None; c::MAX_RESOURCE_VIEWS],
scissor: false,
stencil: None,
cull_face: s::CullFace::Nothing,
//blend: None,
draw_mask: 0,
}
}
}
pub struct CommandBuffer {
pub buf: Vec<Command>,
pub data: DataBuffer,
fbo: FrameBuffer,
cache: Cache,
}
impl CommandBuffer {
pub fn new(fbo: FrameBuffer) -> CommandBuffer {
CommandBuffer {
buf: Vec::new(),
data: DataBuffer::new(),
fbo: fbo,
cache: Cache::new(),
}
}
fn is_main_target(&self, tv: Option<TargetView>) -> bool {
match tv {
Some(TargetView::Surface(0)) | None => true,
Some(_) => false,
}
}
}
impl c::draw::CommandBuffer<Resources> for CommandBuffer {
fn clone_empty(&self) -> CommandBuffer {
CommandBuffer::new(self.fbo)
}
fn reset(&mut self) {
self.buf.clear();
self.data.0.clear();
self.cache = Cache::new();
}
fn bind_pipeline_state(&mut self, pso: PipelineState) {
let cull = pso.rasterizer.method.get_cull_face();
self.cache.primitive = primitive_to_gl(pso.primitive);
self.cache.attributes = pso.input;
self.cache.stencil = pso.output.stencil;
self.cache.cull_face = cull;
self.cache.draw_mask = pso.output.draw_mask;
self.buf.push(Command::BindProgram(pso.program));
self.cache.scissor = pso.scissor;
self.buf.push(Command::SetRasterizer(pso.rasterizer));
self.buf.push(Command::SetDepthState(pso.output.depth));
self.buf.push(Command::SetStencilState(pso.output.stencil, (0, 0), cull));
for i in 0.. c::MAX_COLOR_TARGETS {
if pso.output.draw_mask & (1<<i)!= 0 {
self.buf.push(Command::SetBlendState(i as c::ColorSlot, pso.output.colors[i]));
}
}
}
fn bind_vertex_buffers(&mut self, vbs: c::pso::VertexBufferSet<Resources>) {
for i in 0.. c::MAX_VERTEX_ATTRIBUTES {
match (vbs.0[i], self.cache.attributes[i]) {
(None, Some(fm)) => {
error!("No vertex input provided for slot {} of format {:?}", i, fm)
},
(Some((buffer, offset)), Some(mut format)) => {
format.0.offset += offset as gl::types::GLuint;
self.buf.push(Command::BindAttribute(i as c::AttributeSlot, buffer, format));
},
(_, None) => (),
}
}
}
fn bind_constant_buffers(&mut self, cbs: &[c::pso::ConstantBufferParam<Resources>]) {
for param in cbs.iter() {
self.buf.push(Command::BindConstantBuffer(param.clone()));
}
}
fn bind_global_constant(&mut self, loc: c::shade::Location,
value: c::shade::UniformValue) {
self.buf.push(Command::BindUniform(loc, value));
}
fn bind_resource_views(&mut self, srvs: &[c::pso::ResourceViewParam<Resources>]) {
for i in 0.. c::MAX_RESOURCE_VIEWS {
self.cache.resource_binds[i] = None;
}
for param in srvs.iter() {
self.cache.resource_binds[param.2 as usize] = Some(param.0.bind);
self.buf.push(Command::BindResourceView(param.clone()));
}
}
fn bind_unordered_views(&mut self, uavs: &[c::pso::UnorderedViewParam<Resources>]) {
for param in uavs.iter() {
self.buf.push(Command::BindUnorderedView(param.clone()));
}
}
fn bind_samplers(&mut self, ss: &[c::pso::SamplerParam<Resources>]) {
for param in ss.iter() {
let bind = self.cache.resource_binds[param.2 as usize];
self.buf.push(Command::BindSampler(param.clone(), bind));
}
}
fn bind_pixel_targets(&mut self, pts: c::pso::PixelTargetSet<Resources>) {
let is_main = pts.colors.iter().skip(1).find(|c| c.is_some()).is_none() &&
self.is_main_target(pts.colors[0]) &&
self.is_main_target(pts.depth) &&
self.is_main_target(pts.stencil);
if is_main {
self.buf.push(Command::BindFrameBuffer(gl::DRAW_FRAMEBUFFER, 0));
}else {
let num = pts.colors.iter().position(|c| c.is_none())
.unwrap_or(pts.colors.len()) as c::ColorSlot;
self.buf.push(Command::BindFrameBuffer(gl::DRAW_FRAMEBUFFER, self.fbo));
self.buf.push(Command::BindPixelTargets(pts));
self.buf.push(Command::SetDrawColorBuffers(num));
}
self.buf.push(Command::SetViewport(Rect {
x: 0, y: 0, w: pts.size.0, h: pts.size.1}));
}
fn bind_index(&mut self, buf: Buffer, itype: c::IndexType) {
self.cache.index_type = itype;
self.buf.push(Command::BindIndex(buf));
}
fn set_scissor(&mut self, rect: Rect) {
self.buf.push(Command::SetScissor(
|
fn set_ref_values(&mut self, rv: s::RefValues) {
self.buf.push(Command::SetStencilState(self.cache.stencil, rv.stencil, self.cache.cull_face));
self.buf.push(Command::SetBlendColor(rv.blend));
}
fn update_buffer(&mut self, buf: Buffer, data: &[u8], offset_bytes: usize) {
let ptr = self.data.add(data);
self.buf.push(Command::UpdateBuffer(buf, ptr, offset_bytes));
}
fn update_texture(&mut self, ntex: NewTexture, kind: c::tex::Kind,
face: Option<c::tex::CubeFace>, data: &[u8],
img: c::tex::RawImageInfo) {
let ptr = self.data.add(data);
match ntex {
NewTexture::Texture(t) =>
self.buf.push(Command::UpdateTexture(t, kind, face, ptr, img)),
NewTexture::Surface(s) =>
error!("GL: unable to update the contents of a Surface({})", s),
}
}
fn generate_mipmap(&mut self, srv: ResourceView) {
self.buf.push(Command::GenerateMipmap(srv));
}
fn clear_color(&mut self, target: TargetView, value: draw::ClearColor) {
// this could be optimized by deferring the actual clear call
let mut pts = c::pso::PixelTargetSet::new();
pts.colors[0] = Some(target);
self.bind_pixel_targets(pts);
self.buf.push(Command::Clear(Some(value), None, None));
}
fn clear_depth_stencil(&mut self, target: TargetView, depth: Option<Depth>, stencil: Option<Stencil>) {
let mut pts = c::pso::PixelTargetSet::new();
if depth.is_some() {
pts.depth = Some(target);
}
if stencil.is_some() {
pts.stencil = Some(target);
}
self.bind_pixel_targets(pts);
self.buf.push(Command::Clear(None, depth, stencil));
}
fn call_draw(&mut self, start: c::VertexCount,
count: c::VertexCount, instances: draw::InstanceOption) {
self.buf.push(Command::Draw(self.cache.primitive, start, count, instances));
}
fn call_draw_indexed(&mut self, start: c::VertexCount,
count: c::VertexCount, base: c::VertexCount,
instances: draw::InstanceOption) {
let (offset, gl_index) = match self.cache.index_type {
c::IndexType::U8 => (start * 1u32, gl::UNSIGNED_BYTE),
c::IndexType::U16 => (start * 2u32, gl::UNSIGNED_SHORT),
c::IndexType::U32 => (start * 4u32, gl::UNSIGNED_INT),
};
self.buf.push(Command::DrawIndexed(self.cache.primitive,
gl_index, RawOffset(offset as *const gl::types::GLvoid), count, base, instances));
}
}
|
if self.cache.scissor {Some(rect)} else {None}
));
}
|
random_line_split
|
command.rs
|
// Copyright 2015 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#![allow(missing_docs)]
use gl;
use gfx_core as c;
use gfx_core::draw;
use gfx_core::state as s;
use gfx_core::target::{ColorValue, Depth, Mirror, Rect, Stencil};
use {Buffer, Program, FrameBuffer, Texture,
NewTexture, Resources, PipelineState, ResourceView, TargetView};
fn primitive_to_gl(primitive: c::Primitive) -> gl::types::GLenum {
use gfx_core::Primitive::*;
match primitive {
PointList => gl::POINTS,
LineList => gl::LINES,
LineStrip => gl::LINE_STRIP,
TriangleList => gl::TRIANGLES,
TriangleStrip => gl::TRIANGLE_STRIP,
//TriangleFan => gl::TRIANGLE_FAN,
}
}
pub type Access = gl::types::GLenum;
#[derive(Clone, Copy, Debug)]
pub struct RawOffset(pub *const gl::types::GLvoid);
unsafe impl Send for RawOffset {}
/// The place of some data in the data buffer.
#[derive(Clone, Copy, PartialEq, Debug)]
pub struct DataPointer {
offset: u32,
size: u32,
}
pub struct DataBuffer(Vec<u8>);
impl DataBuffer {
/// Create a new empty data buffer.
pub fn new() -> DataBuffer {
DataBuffer(Vec::new())
}
/// Copy a given vector slice into the buffer.
fn add(&mut self, data: &[u8]) -> DataPointer {
self.0.extend_from_slice(data);
DataPointer {
offset: (self.0.len() - data.len()) as u32,
size: data.len() as u32,
}
}
/// Return a reference to a stored data object.
pub fn get(&self, ptr: DataPointer) -> &[u8] {
&self.0[ptr.offset as usize.. (ptr.offset + ptr.size) as usize]
}
}
///Serialized device command.
#[derive(Clone, Copy, Debug)]
pub enum Command {
// states
BindProgram(Program),
BindConstantBuffer(c::pso::ConstantBufferParam<Resources>),
BindResourceView(c::pso::ResourceViewParam<Resources>),
BindUnorderedView(c::pso::UnorderedViewParam<Resources>),
BindSampler(c::pso::SamplerParam<Resources>, Option<gl::types::GLenum>),
BindPixelTargets(c::pso::PixelTargetSet<Resources>),
BindAttribute(c::AttributeSlot, Buffer, c::pso::AttributeDesc),
BindIndex(Buffer),
BindFrameBuffer(Access, FrameBuffer),
BindUniform(c::shade::Location, c::shade::UniformValue),
SetDrawColorBuffers(c::ColorSlot),
SetRasterizer(s::Rasterizer),
SetViewport(Rect),
SetScissor(Option<Rect>),
SetDepthState(Option<s::Depth>),
SetStencilState(Option<s::Stencil>, (Stencil, Stencil), s::CullFace),
SetBlendState(c::ColorSlot, s::Color),
SetBlendColor(ColorValue),
// resource updates
UpdateBuffer(Buffer, DataPointer, usize),
UpdateTexture(Texture, c::tex::Kind, Option<c::tex::CubeFace>,
DataPointer, c::tex::RawImageInfo),
GenerateMipmap(ResourceView),
// drawing
Clear(Option<draw::ClearColor>, Option<Depth>, Option<Stencil>),
Draw(gl::types::GLenum, c::VertexCount, c::VertexCount, draw::InstanceOption),
DrawIndexed(gl::types::GLenum, gl::types::GLenum, RawOffset,
c::VertexCount, c::VertexCount, draw::InstanceOption),
_Blit(Rect, Rect, Mirror, usize),
}
pub const COLOR_DEFAULT: s::Color = s::Color {
mask: s::MASK_ALL,
blend: None,
};
pub const RESET: [Command; 13] = [
Command::BindProgram(0),
// BindAttribute
Command::BindIndex(0),
Command::BindFrameBuffer(gl::FRAMEBUFFER, 0),
Command::SetRasterizer(s::Rasterizer {
front_face: s::FrontFace::CounterClockwise,
method: s::RasterMethod::Fill(s::CullFace::Back),
offset: None,
samples: None,
}),
Command::SetViewport(Rect{x: 0, y: 0, w: 0, h: 0}),
Command::SetScissor(None),
Command::SetDepthState(None),
Command::SetStencilState(None, (0, 0), s::CullFace::Nothing),
Command::SetBlendState(0, COLOR_DEFAULT),
Command::SetBlendState(1, COLOR_DEFAULT),
Command::SetBlendState(2, COLOR_DEFAULT),
Command::SetBlendState(3, COLOR_DEFAULT),
Command::SetBlendColor([0f32; 4]),
];
struct Cache {
primitive: gl::types::GLenum,
index_type: c::IndexType,
attributes: [Option<c::pso::AttributeDesc>; c::MAX_VERTEX_ATTRIBUTES],
resource_binds: [Option<gl::types::GLenum>; c::MAX_RESOURCE_VIEWS],
scissor: bool,
stencil: Option<s::Stencil>,
//blend: Option<s::Blend>,
cull_face: s::CullFace,
draw_mask: u32,
}
impl Cache {
pub fn new() -> Cache {
Cache {
primitive: 0,
index_type: c::IndexType::U8,
attributes: [None; c::MAX_VERTEX_ATTRIBUTES],
resource_binds: [None; c::MAX_RESOURCE_VIEWS],
scissor: false,
stencil: None,
cull_face: s::CullFace::Nothing,
//blend: None,
draw_mask: 0,
}
}
}
pub struct CommandBuffer {
pub buf: Vec<Command>,
pub data: DataBuffer,
fbo: FrameBuffer,
cache: Cache,
}
impl CommandBuffer {
pub fn new(fbo: FrameBuffer) -> CommandBuffer {
CommandBuffer {
buf: Vec::new(),
data: DataBuffer::new(),
fbo: fbo,
cache: Cache::new(),
}
}
fn is_main_target(&self, tv: Option<TargetView>) -> bool {
match tv {
Some(TargetView::Surface(0)) | None => true,
Some(_) => false,
}
}
}
impl c::draw::CommandBuffer<Resources> for CommandBuffer {
fn clone_empty(&self) -> CommandBuffer {
CommandBuffer::new(self.fbo)
}
fn reset(&mut self) {
self.buf.clear();
self.data.0.clear();
self.cache = Cache::new();
}
fn bind_pipeline_state(&mut self, pso: PipelineState) {
let cull = pso.rasterizer.method.get_cull_face();
self.cache.primitive = primitive_to_gl(pso.primitive);
self.cache.attributes = pso.input;
self.cache.stencil = pso.output.stencil;
self.cache.cull_face = cull;
self.cache.draw_mask = pso.output.draw_mask;
self.buf.push(Command::BindProgram(pso.program));
self.cache.scissor = pso.scissor;
self.buf.push(Command::SetRasterizer(pso.rasterizer));
self.buf.push(Command::SetDepthState(pso.output.depth));
self.buf.push(Command::SetStencilState(pso.output.stencil, (0, 0), cull));
for i in 0.. c::MAX_COLOR_TARGETS {
if pso.output.draw_mask & (1<<i)!= 0 {
self.buf.push(Command::SetBlendState(i as c::ColorSlot, pso.output.colors[i]));
}
}
}
fn bind_vertex_buffers(&mut self, vbs: c::pso::VertexBufferSet<Resources>) {
for i in 0.. c::MAX_VERTEX_ATTRIBUTES {
match (vbs.0[i], self.cache.attributes[i]) {
(None, Some(fm)) => {
error!("No vertex input provided for slot {} of format {:?}", i, fm)
},
(Some((buffer, offset)), Some(mut format)) => {
format.0.offset += offset as gl::types::GLuint;
self.buf.push(Command::BindAttribute(i as c::AttributeSlot, buffer, format));
},
(_, None) => (),
}
}
}
fn bind_constant_buffers(&mut self, cbs: &[c::pso::ConstantBufferParam<Resources>]) {
for param in cbs.iter() {
self.buf.push(Command::BindConstantBuffer(param.clone()));
}
}
fn bind_global_constant(&mut self, loc: c::shade::Location,
value: c::shade::UniformValue) {
self.buf.push(Command::BindUniform(loc, value));
}
fn bind_resource_views(&mut self, srvs: &[c::pso::ResourceViewParam<Resources>]) {
for i in 0.. c::MAX_RESOURCE_VIEWS {
self.cache.resource_binds[i] = None;
}
for param in srvs.iter() {
self.cache.resource_binds[param.2 as usize] = Some(param.0.bind);
self.buf.push(Command::BindResourceView(param.clone()));
}
}
fn bind_unordered_views(&mut self, uavs: &[c::pso::UnorderedViewParam<Resources>]) {
for param in uavs.iter() {
self.buf.push(Command::BindUnorderedView(param.clone()));
}
}
fn bind_samplers(&mut self, ss: &[c::pso::SamplerParam<Resources>]) {
for param in ss.iter() {
let bind = self.cache.resource_binds[param.2 as usize];
self.buf.push(Command::BindSampler(param.clone(), bind));
}
}
fn bind_pixel_targets(&mut self, pts: c::pso::PixelTargetSet<Resources>) {
let is_main = pts.colors.iter().skip(1).find(|c| c.is_some()).is_none() &&
self.is_main_target(pts.colors[0]) &&
self.is_main_target(pts.depth) &&
self.is_main_target(pts.stencil);
if is_main {
self.buf.push(Command::BindFrameBuffer(gl::DRAW_FRAMEBUFFER, 0));
}else {
let num = pts.colors.iter().position(|c| c.is_none())
.unwrap_or(pts.colors.len()) as c::ColorSlot;
self.buf.push(Command::BindFrameBuffer(gl::DRAW_FRAMEBUFFER, self.fbo));
self.buf.push(Command::BindPixelTargets(pts));
self.buf.push(Command::SetDrawColorBuffers(num));
}
self.buf.push(Command::SetViewport(Rect {
x: 0, y: 0, w: pts.size.0, h: pts.size.1}));
}
fn bind_index(&mut self, buf: Buffer, itype: c::IndexType) {
self.cache.index_type = itype;
self.buf.push(Command::BindIndex(buf));
}
fn set_scissor(&mut self, rect: Rect) {
self.buf.push(Command::SetScissor(
if self.cache.scissor
|
else {None}
));
}
fn set_ref_values(&mut self, rv: s::RefValues) {
self.buf.push(Command::SetStencilState(self.cache.stencil, rv.stencil, self.cache.cull_face));
self.buf.push(Command::SetBlendColor(rv.blend));
}
fn update_buffer(&mut self, buf: Buffer, data: &[u8], offset_bytes: usize) {
let ptr = self.data.add(data);
self.buf.push(Command::UpdateBuffer(buf, ptr, offset_bytes));
}
fn update_texture(&mut self, ntex: NewTexture, kind: c::tex::Kind,
face: Option<c::tex::CubeFace>, data: &[u8],
img: c::tex::RawImageInfo) {
let ptr = self.data.add(data);
match ntex {
NewTexture::Texture(t) =>
self.buf.push(Command::UpdateTexture(t, kind, face, ptr, img)),
NewTexture::Surface(s) =>
error!("GL: unable to update the contents of a Surface({})", s),
}
}
fn generate_mipmap(&mut self, srv: ResourceView) {
self.buf.push(Command::GenerateMipmap(srv));
}
fn clear_color(&mut self, target: TargetView, value: draw::ClearColor) {
// this could be optimized by deferring the actual clear call
let mut pts = c::pso::PixelTargetSet::new();
pts.colors[0] = Some(target);
self.bind_pixel_targets(pts);
self.buf.push(Command::Clear(Some(value), None, None));
}
fn clear_depth_stencil(&mut self, target: TargetView, depth: Option<Depth>, stencil: Option<Stencil>) {
let mut pts = c::pso::PixelTargetSet::new();
if depth.is_some() {
pts.depth = Some(target);
}
if stencil.is_some() {
pts.stencil = Some(target);
}
self.bind_pixel_targets(pts);
self.buf.push(Command::Clear(None, depth, stencil));
}
fn call_draw(&mut self, start: c::VertexCount,
count: c::VertexCount, instances: draw::InstanceOption) {
self.buf.push(Command::Draw(self.cache.primitive, start, count, instances));
}
fn call_draw_indexed(&mut self, start: c::VertexCount,
count: c::VertexCount, base: c::VertexCount,
instances: draw::InstanceOption) {
let (offset, gl_index) = match self.cache.index_type {
c::IndexType::U8 => (start * 1u32, gl::UNSIGNED_BYTE),
c::IndexType::U16 => (start * 2u32, gl::UNSIGNED_SHORT),
c::IndexType::U32 => (start * 4u32, gl::UNSIGNED_INT),
};
self.buf.push(Command::DrawIndexed(self.cache.primitive,
gl_index, RawOffset(offset as *const gl::types::GLvoid), count, base, instances));
}
}
|
{Some(rect)}
|
conditional_block
|
command.rs
|
// Copyright 2015 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#![allow(missing_docs)]
use gl;
use gfx_core as c;
use gfx_core::draw;
use gfx_core::state as s;
use gfx_core::target::{ColorValue, Depth, Mirror, Rect, Stencil};
use {Buffer, Program, FrameBuffer, Texture,
NewTexture, Resources, PipelineState, ResourceView, TargetView};
fn primitive_to_gl(primitive: c::Primitive) -> gl::types::GLenum
|
pub type Access = gl::types::GLenum;
#[derive(Clone, Copy, Debug)]
pub struct RawOffset(pub *const gl::types::GLvoid);
unsafe impl Send for RawOffset {}
/// The place of some data in the data buffer.
#[derive(Clone, Copy, PartialEq, Debug)]
pub struct DataPointer {
offset: u32,
size: u32,
}
pub struct DataBuffer(Vec<u8>);
impl DataBuffer {
/// Create a new empty data buffer.
pub fn new() -> DataBuffer {
DataBuffer(Vec::new())
}
/// Copy a given vector slice into the buffer.
fn add(&mut self, data: &[u8]) -> DataPointer {
self.0.extend_from_slice(data);
DataPointer {
offset: (self.0.len() - data.len()) as u32,
size: data.len() as u32,
}
}
/// Return a reference to a stored data object.
pub fn get(&self, ptr: DataPointer) -> &[u8] {
&self.0[ptr.offset as usize.. (ptr.offset + ptr.size) as usize]
}
}
///Serialized device command.
#[derive(Clone, Copy, Debug)]
pub enum Command {
// states
BindProgram(Program),
BindConstantBuffer(c::pso::ConstantBufferParam<Resources>),
BindResourceView(c::pso::ResourceViewParam<Resources>),
BindUnorderedView(c::pso::UnorderedViewParam<Resources>),
BindSampler(c::pso::SamplerParam<Resources>, Option<gl::types::GLenum>),
BindPixelTargets(c::pso::PixelTargetSet<Resources>),
BindAttribute(c::AttributeSlot, Buffer, c::pso::AttributeDesc),
BindIndex(Buffer),
BindFrameBuffer(Access, FrameBuffer),
BindUniform(c::shade::Location, c::shade::UniformValue),
SetDrawColorBuffers(c::ColorSlot),
SetRasterizer(s::Rasterizer),
SetViewport(Rect),
SetScissor(Option<Rect>),
SetDepthState(Option<s::Depth>),
SetStencilState(Option<s::Stencil>, (Stencil, Stencil), s::CullFace),
SetBlendState(c::ColorSlot, s::Color),
SetBlendColor(ColorValue),
// resource updates
UpdateBuffer(Buffer, DataPointer, usize),
UpdateTexture(Texture, c::tex::Kind, Option<c::tex::CubeFace>,
DataPointer, c::tex::RawImageInfo),
GenerateMipmap(ResourceView),
// drawing
Clear(Option<draw::ClearColor>, Option<Depth>, Option<Stencil>),
Draw(gl::types::GLenum, c::VertexCount, c::VertexCount, draw::InstanceOption),
DrawIndexed(gl::types::GLenum, gl::types::GLenum, RawOffset,
c::VertexCount, c::VertexCount, draw::InstanceOption),
_Blit(Rect, Rect, Mirror, usize),
}
pub const COLOR_DEFAULT: s::Color = s::Color {
mask: s::MASK_ALL,
blend: None,
};
pub const RESET: [Command; 13] = [
Command::BindProgram(0),
// BindAttribute
Command::BindIndex(0),
Command::BindFrameBuffer(gl::FRAMEBUFFER, 0),
Command::SetRasterizer(s::Rasterizer {
front_face: s::FrontFace::CounterClockwise,
method: s::RasterMethod::Fill(s::CullFace::Back),
offset: None,
samples: None,
}),
Command::SetViewport(Rect{x: 0, y: 0, w: 0, h: 0}),
Command::SetScissor(None),
Command::SetDepthState(None),
Command::SetStencilState(None, (0, 0), s::CullFace::Nothing),
Command::SetBlendState(0, COLOR_DEFAULT),
Command::SetBlendState(1, COLOR_DEFAULT),
Command::SetBlendState(2, COLOR_DEFAULT),
Command::SetBlendState(3, COLOR_DEFAULT),
Command::SetBlendColor([0f32; 4]),
];
struct Cache {
primitive: gl::types::GLenum,
index_type: c::IndexType,
attributes: [Option<c::pso::AttributeDesc>; c::MAX_VERTEX_ATTRIBUTES],
resource_binds: [Option<gl::types::GLenum>; c::MAX_RESOURCE_VIEWS],
scissor: bool,
stencil: Option<s::Stencil>,
//blend: Option<s::Blend>,
cull_face: s::CullFace,
draw_mask: u32,
}
impl Cache {
pub fn new() -> Cache {
Cache {
primitive: 0,
index_type: c::IndexType::U8,
attributes: [None; c::MAX_VERTEX_ATTRIBUTES],
resource_binds: [None; c::MAX_RESOURCE_VIEWS],
scissor: false,
stencil: None,
cull_face: s::CullFace::Nothing,
//blend: None,
draw_mask: 0,
}
}
}
pub struct CommandBuffer {
pub buf: Vec<Command>,
pub data: DataBuffer,
fbo: FrameBuffer,
cache: Cache,
}
impl CommandBuffer {
pub fn new(fbo: FrameBuffer) -> CommandBuffer {
CommandBuffer {
buf: Vec::new(),
data: DataBuffer::new(),
fbo: fbo,
cache: Cache::new(),
}
}
fn is_main_target(&self, tv: Option<TargetView>) -> bool {
match tv {
Some(TargetView::Surface(0)) | None => true,
Some(_) => false,
}
}
}
impl c::draw::CommandBuffer<Resources> for CommandBuffer {
fn clone_empty(&self) -> CommandBuffer {
CommandBuffer::new(self.fbo)
}
fn reset(&mut self) {
self.buf.clear();
self.data.0.clear();
self.cache = Cache::new();
}
fn bind_pipeline_state(&mut self, pso: PipelineState) {
let cull = pso.rasterizer.method.get_cull_face();
self.cache.primitive = primitive_to_gl(pso.primitive);
self.cache.attributes = pso.input;
self.cache.stencil = pso.output.stencil;
self.cache.cull_face = cull;
self.cache.draw_mask = pso.output.draw_mask;
self.buf.push(Command::BindProgram(pso.program));
self.cache.scissor = pso.scissor;
self.buf.push(Command::SetRasterizer(pso.rasterizer));
self.buf.push(Command::SetDepthState(pso.output.depth));
self.buf.push(Command::SetStencilState(pso.output.stencil, (0, 0), cull));
for i in 0.. c::MAX_COLOR_TARGETS {
if pso.output.draw_mask & (1<<i)!= 0 {
self.buf.push(Command::SetBlendState(i as c::ColorSlot, pso.output.colors[i]));
}
}
}
fn bind_vertex_buffers(&mut self, vbs: c::pso::VertexBufferSet<Resources>) {
for i in 0.. c::MAX_VERTEX_ATTRIBUTES {
match (vbs.0[i], self.cache.attributes[i]) {
(None, Some(fm)) => {
error!("No vertex input provided for slot {} of format {:?}", i, fm)
},
(Some((buffer, offset)), Some(mut format)) => {
format.0.offset += offset as gl::types::GLuint;
self.buf.push(Command::BindAttribute(i as c::AttributeSlot, buffer, format));
},
(_, None) => (),
}
}
}
fn bind_constant_buffers(&mut self, cbs: &[c::pso::ConstantBufferParam<Resources>]) {
for param in cbs.iter() {
self.buf.push(Command::BindConstantBuffer(param.clone()));
}
}
fn bind_global_constant(&mut self, loc: c::shade::Location,
value: c::shade::UniformValue) {
self.buf.push(Command::BindUniform(loc, value));
}
fn bind_resource_views(&mut self, srvs: &[c::pso::ResourceViewParam<Resources>]) {
for i in 0.. c::MAX_RESOURCE_VIEWS {
self.cache.resource_binds[i] = None;
}
for param in srvs.iter() {
self.cache.resource_binds[param.2 as usize] = Some(param.0.bind);
self.buf.push(Command::BindResourceView(param.clone()));
}
}
fn bind_unordered_views(&mut self, uavs: &[c::pso::UnorderedViewParam<Resources>]) {
for param in uavs.iter() {
self.buf.push(Command::BindUnorderedView(param.clone()));
}
}
fn bind_samplers(&mut self, ss: &[c::pso::SamplerParam<Resources>]) {
for param in ss.iter() {
let bind = self.cache.resource_binds[param.2 as usize];
self.buf.push(Command::BindSampler(param.clone(), bind));
}
}
fn bind_pixel_targets(&mut self, pts: c::pso::PixelTargetSet<Resources>) {
let is_main = pts.colors.iter().skip(1).find(|c| c.is_some()).is_none() &&
self.is_main_target(pts.colors[0]) &&
self.is_main_target(pts.depth) &&
self.is_main_target(pts.stencil);
if is_main {
self.buf.push(Command::BindFrameBuffer(gl::DRAW_FRAMEBUFFER, 0));
}else {
let num = pts.colors.iter().position(|c| c.is_none())
.unwrap_or(pts.colors.len()) as c::ColorSlot;
self.buf.push(Command::BindFrameBuffer(gl::DRAW_FRAMEBUFFER, self.fbo));
self.buf.push(Command::BindPixelTargets(pts));
self.buf.push(Command::SetDrawColorBuffers(num));
}
self.buf.push(Command::SetViewport(Rect {
x: 0, y: 0, w: pts.size.0, h: pts.size.1}));
}
fn bind_index(&mut self, buf: Buffer, itype: c::IndexType) {
self.cache.index_type = itype;
self.buf.push(Command::BindIndex(buf));
}
fn set_scissor(&mut self, rect: Rect) {
self.buf.push(Command::SetScissor(
if self.cache.scissor {Some(rect)} else {None}
));
}
fn set_ref_values(&mut self, rv: s::RefValues) {
self.buf.push(Command::SetStencilState(self.cache.stencil, rv.stencil, self.cache.cull_face));
self.buf.push(Command::SetBlendColor(rv.blend));
}
fn update_buffer(&mut self, buf: Buffer, data: &[u8], offset_bytes: usize) {
let ptr = self.data.add(data);
self.buf.push(Command::UpdateBuffer(buf, ptr, offset_bytes));
}
fn update_texture(&mut self, ntex: NewTexture, kind: c::tex::Kind,
face: Option<c::tex::CubeFace>, data: &[u8],
img: c::tex::RawImageInfo) {
let ptr = self.data.add(data);
match ntex {
NewTexture::Texture(t) =>
self.buf.push(Command::UpdateTexture(t, kind, face, ptr, img)),
NewTexture::Surface(s) =>
error!("GL: unable to update the contents of a Surface({})", s),
}
}
fn generate_mipmap(&mut self, srv: ResourceView) {
self.buf.push(Command::GenerateMipmap(srv));
}
fn clear_color(&mut self, target: TargetView, value: draw::ClearColor) {
// this could be optimized by deferring the actual clear call
let mut pts = c::pso::PixelTargetSet::new();
pts.colors[0] = Some(target);
self.bind_pixel_targets(pts);
self.buf.push(Command::Clear(Some(value), None, None));
}
fn clear_depth_stencil(&mut self, target: TargetView, depth: Option<Depth>, stencil: Option<Stencil>) {
let mut pts = c::pso::PixelTargetSet::new();
if depth.is_some() {
pts.depth = Some(target);
}
if stencil.is_some() {
pts.stencil = Some(target);
}
self.bind_pixel_targets(pts);
self.buf.push(Command::Clear(None, depth, stencil));
}
fn call_draw(&mut self, start: c::VertexCount,
count: c::VertexCount, instances: draw::InstanceOption) {
self.buf.push(Command::Draw(self.cache.primitive, start, count, instances));
}
fn call_draw_indexed(&mut self, start: c::VertexCount,
count: c::VertexCount, base: c::VertexCount,
instances: draw::InstanceOption) {
let (offset, gl_index) = match self.cache.index_type {
c::IndexType::U8 => (start * 1u32, gl::UNSIGNED_BYTE),
c::IndexType::U16 => (start * 2u32, gl::UNSIGNED_SHORT),
c::IndexType::U32 => (start * 4u32, gl::UNSIGNED_INT),
};
self.buf.push(Command::DrawIndexed(self.cache.primitive,
gl_index, RawOffset(offset as *const gl::types::GLvoid), count, base, instances));
}
}
|
{
use gfx_core::Primitive::*;
match primitive {
PointList => gl::POINTS,
LineList => gl::LINES,
LineStrip => gl::LINE_STRIP,
TriangleList => gl::TRIANGLES,
TriangleStrip => gl::TRIANGLE_STRIP,
//TriangleFan => gl::TRIANGLE_FAN,
}
}
|
identifier_body
|
alignment-gep-tup-like-2.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.
#[feature(managed_boxes)];
struct Pair<A,B> {
a: A, b: B
}
struct RecEnum<A>(Rec<A>);
struct Rec<A> {
val: A,
rec: Option<@mut RecEnum<A>>
}
fn make_cycle<A:'static>(a: A) {
let g: @mut RecEnum<A> = @mut RecEnum(Rec {val: a, rec: None});
g.rec = Some(g);
}
struct Invoker<A,B> {
a: A,
b: B,
}
trait Invokable<A,B> {
fn f(&self) -> (A, B);
}
impl<A:Clone,B:Clone> Invokable<A,B> for Invoker<A,B> {
fn
|
(&self) -> (A, B) {
(self.a.clone(), self.b.clone())
}
}
fn f<A:Send + Clone +'static,
B:Send + Clone +'static>(
a: A,
b: B)
-> @Invokable<A,B> {
@Invoker {
a: a,
b: b,
} as @Invokable<A,B>
}
pub fn main() {
let x = 22_u8;
let y = 44_u64;
let z = f(~x, y);
make_cycle(z);
let (a, b) = z.f();
info!("a={} b={}", *a as uint, b as uint);
assert_eq!(*a, x);
assert_eq!(b, y);
}
|
f
|
identifier_name
|
alignment-gep-tup-like-2.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.
#[feature(managed_boxes)];
struct Pair<A,B> {
a: A, b: B
}
struct RecEnum<A>(Rec<A>);
struct Rec<A> {
val: A,
rec: Option<@mut RecEnum<A>>
}
fn make_cycle<A:'static>(a: A) {
let g: @mut RecEnum<A> = @mut RecEnum(Rec {val: a, rec: None});
g.rec = Some(g);
}
struct Invoker<A,B> {
a: A,
b: B,
}
trait Invokable<A,B> {
fn f(&self) -> (A, B);
}
impl<A:Clone,B:Clone> Invokable<A,B> for Invoker<A,B> {
fn f(&self) -> (A, B) {
(self.a.clone(), self.b.clone())
}
}
fn f<A:Send + Clone +'static,
|
-> @Invokable<A,B> {
@Invoker {
a: a,
b: b,
} as @Invokable<A,B>
}
pub fn main() {
let x = 22_u8;
let y = 44_u64;
let z = f(~x, y);
make_cycle(z);
let (a, b) = z.f();
info!("a={} b={}", *a as uint, b as uint);
assert_eq!(*a, x);
assert_eq!(b, y);
}
|
B:Send + Clone + 'static>(
a: A,
b: B)
|
random_line_split
|
hmacsha256.rs
|
//! `HMAC-SHA-256` `HMAC-SHA-256` is conjectured to meet the standard notion of
//! unforgeability.
use ffi::{crypto_auth_hmacsha256,
crypto_auth_hmacsha256_verify,
crypto_auth_hmacsha256_KEYBYTES,
crypto_auth_hmacsha256_BYTES
};
use crypto::verify::verify_32;
auth_module!(crypto_auth_hmacsha256,
crypto_auth_hmacsha256_verify,
verify_32,
crypto_auth_hmacsha256_KEYBYTES,
crypto_auth_hmacsha256_BYTES);
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_vector_1()
|
}
|
{
// corresponding to tests/auth2.c from NaCl
let key = Key([0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08
,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f,0x10
,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18
,0x19,0x1a,0x1b,0x1c,0x1d,0x1e,0x1f,0x20]);
let c = [0xcd,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd
,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd
,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd
,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd
,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd
,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd
,0xcd,0xcd];
let a_expected = Tag([0x37,0x2e,0xfc,0xf9,0xb4,0x0b,0x35,0xc2
,0x11,0x5b,0x13,0x46,0x90,0x3d,0x2e,0xf4
,0x2f,0xce,0xd4,0x6f,0x08,0x46,0xe7,0x25
,0x7b,0xb1,0x56,0xd3,0xd7,0xb3,0x0d,0x3f]);
let a = authenticate(&c, &key);
assert!(a == a_expected);
}
|
identifier_body
|
hmacsha256.rs
|
//! `HMAC-SHA-256` `HMAC-SHA-256` is conjectured to meet the standard notion of
//! unforgeability.
use ffi::{crypto_auth_hmacsha256,
crypto_auth_hmacsha256_verify,
crypto_auth_hmacsha256_KEYBYTES,
crypto_auth_hmacsha256_BYTES
};
use crypto::verify::verify_32;
auth_module!(crypto_auth_hmacsha256,
crypto_auth_hmacsha256_verify,
verify_32,
crypto_auth_hmacsha256_KEYBYTES,
crypto_auth_hmacsha256_BYTES);
#[cfg(test)]
mod test {
use super::*;
#[test]
fn
|
() {
// corresponding to tests/auth2.c from NaCl
let key = Key([0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08
,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f,0x10
,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18
,0x19,0x1a,0x1b,0x1c,0x1d,0x1e,0x1f,0x20]);
let c = [0xcd,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd
,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd
,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd
,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd
,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd
,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd
,0xcd,0xcd];
let a_expected = Tag([0x37,0x2e,0xfc,0xf9,0xb4,0x0b,0x35,0xc2
,0x11,0x5b,0x13,0x46,0x90,0x3d,0x2e,0xf4
,0x2f,0xce,0xd4,0x6f,0x08,0x46,0xe7,0x25
,0x7b,0xb1,0x56,0xd3,0xd7,0xb3,0x0d,0x3f]);
let a = authenticate(&c, &key);
assert!(a == a_expected);
}
}
|
test_vector_1
|
identifier_name
|
hmacsha256.rs
|
//! `HMAC-SHA-256` `HMAC-SHA-256` is conjectured to meet the standard notion of
//! unforgeability.
use ffi::{crypto_auth_hmacsha256,
crypto_auth_hmacsha256_verify,
crypto_auth_hmacsha256_KEYBYTES,
crypto_auth_hmacsha256_BYTES
};
use crypto::verify::verify_32;
auth_module!(crypto_auth_hmacsha256,
crypto_auth_hmacsha256_verify,
verify_32,
crypto_auth_hmacsha256_KEYBYTES,
crypto_auth_hmacsha256_BYTES);
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_vector_1() {
// corresponding to tests/auth2.c from NaCl
let key = Key([0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08
,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f,0x10
,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18
,0x19,0x1a,0x1b,0x1c,0x1d,0x1e,0x1f,0x20]);
let c = [0xcd,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd
,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd
,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd
,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd
,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd
,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd
,0xcd,0xcd];
let a_expected = Tag([0x37,0x2e,0xfc,0xf9,0xb4,0x0b,0x35,0xc2
|
,0x7b,0xb1,0x56,0xd3,0xd7,0xb3,0x0d,0x3f]);
let a = authenticate(&c, &key);
assert!(a == a_expected);
}
}
|
,0x11,0x5b,0x13,0x46,0x90,0x3d,0x2e,0xf4
,0x2f,0xce,0xd4,0x6f,0x08,0x46,0xe7,0x25
|
random_line_split
|
lines.rs
|
use super::{HorizontalAlign, SectionGlyph, SectionText, VerticalAlign};
use crate::{linebreak::LineBreaker, words::*};
use ab_glyph::*;
use std::iter::{FusedIterator, Iterator, Peekable};
/// A line of `Word`s limited to a max width bound.
#[derive(Default)]
pub(crate) struct
|
{
pub glyphs: Vec<SectionGlyph>,
pub max_v_metrics: VMetrics,
pub rightmost: f32,
}
impl Line {
#[inline]
pub(crate) fn line_height(&self) -> f32 {
self.max_v_metrics.ascent - self.max_v_metrics.descent + self.max_v_metrics.line_gap
}
/// Returns line glyphs positioned on the screen and aligned.
pub fn aligned_on_screen(
mut self,
screen_position: (f32, f32),
h_align: HorizontalAlign,
v_align: VerticalAlign,
) -> Vec<SectionGlyph> {
if self.glyphs.is_empty() {
return Vec::new();
}
// implement v-aligns when they're are supported
let screen_left = match h_align {
HorizontalAlign::Left => point(screen_position.0, screen_position.1),
// - Right alignment attained from left by shifting the line
// leftwards by the rightmost x distance from render position
// - Central alignment is attained from left by shifting the line
// leftwards by half the rightmost x distance from render position
HorizontalAlign::Center | HorizontalAlign::Right => {
let mut shift_left = self.rightmost;
if h_align == HorizontalAlign::Center {
shift_left /= 2.0;
}
point(screen_position.0 - shift_left, screen_position.1)
}
};
let screen_pos = match v_align {
VerticalAlign::Top => screen_left,
VerticalAlign::Center => {
let mut screen_pos = screen_left;
screen_pos.y -= self.line_height() / 2.0;
screen_pos
}
VerticalAlign::Bottom => {
let mut screen_pos = screen_left;
screen_pos.y -= self.line_height();
screen_pos
}
};
self.glyphs
.iter_mut()
.for_each(|sg| sg.glyph.position += screen_pos);
self.glyphs
}
}
/// `Line` iterator.
///
/// Will iterator through `Word` until the next word would break the `width_bound`.
///
/// Note: Will always have at least one word, if possible, even if the word itself
/// breaks the `width_bound`.
pub(crate) struct Lines<'a, 'b, L, F, S>
where
L: LineBreaker,
F: Font,
S: Iterator<Item = SectionText<'a>>,
{
pub(crate) words: Peekable<Words<'a, 'b, L, F, S>>,
pub(crate) width_bound: f32,
}
impl<'a, L, F, S> Iterator for Lines<'a, '_, L, F, S>
where
L: LineBreaker,
F: Font,
S: Iterator<Item = SectionText<'a>>,
{
type Item = Line;
fn next(&mut self) -> Option<Self::Item> {
let mut caret = point(0.0, 0.0);
let mut line = Line::default();
let mut progressed = false;
while let Some(word) = self.words.peek() {
let word_right = caret.x + word.layout_width_no_trail;
// Reduce float errors by using relative "<= width bound" check
let word_in_bounds =
word_right < self.width_bound || approx::relative_eq!(word_right, self.width_bound);
// only if `progressed` means the first word is allowed to overlap the bounds
if!word_in_bounds && progressed {
break;
}
let word = self.words.next().unwrap();
progressed = true;
line.rightmost = word_right;
if (line.glyphs.is_empty() ||!word.glyphs.is_empty())
&& word.max_v_metrics.height() > line.max_v_metrics.height()
{
let diff_y = word.max_v_metrics.ascent - caret.y;
caret.y += diff_y;
// modify all smaller lined glyphs to occupy the new larger line
for SectionGlyph { glyph,.. } in &mut line.glyphs {
glyph.position.y += diff_y;
}
line.max_v_metrics = word.max_v_metrics;
}
line.glyphs.extend(word.glyphs.into_iter().map(|mut sg| {
sg.glyph.position += caret;
sg
}));
caret.x += word.layout_width;
if word.hard_break {
break;
}
}
Some(line).filter(|_| progressed)
}
}
impl<'a, L, F, S> FusedIterator for Lines<'a, '_, L, F, S>
where
L: LineBreaker,
F: Font,
S: Iterator<Item = SectionText<'a>>,
{
}
|
Line
|
identifier_name
|
lines.rs
|
use super::{HorizontalAlign, SectionGlyph, SectionText, VerticalAlign};
use crate::{linebreak::LineBreaker, words::*};
use ab_glyph::*;
use std::iter::{FusedIterator, Iterator, Peekable};
/// A line of `Word`s limited to a max width bound.
#[derive(Default)]
pub(crate) struct Line {
pub glyphs: Vec<SectionGlyph>,
pub max_v_metrics: VMetrics,
pub rightmost: f32,
}
impl Line {
#[inline]
pub(crate) fn line_height(&self) -> f32 {
self.max_v_metrics.ascent - self.max_v_metrics.descent + self.max_v_metrics.line_gap
}
/// Returns line glyphs positioned on the screen and aligned.
pub fn aligned_on_screen(
mut self,
screen_position: (f32, f32),
h_align: HorizontalAlign,
v_align: VerticalAlign,
) -> Vec<SectionGlyph> {
if self.glyphs.is_empty() {
return Vec::new();
}
// implement v-aligns when they're are supported
let screen_left = match h_align {
HorizontalAlign::Left => point(screen_position.0, screen_position.1),
// - Right alignment attained from left by shifting the line
// leftwards by the rightmost x distance from render position
// - Central alignment is attained from left by shifting the line
// leftwards by half the rightmost x distance from render position
HorizontalAlign::Center | HorizontalAlign::Right => {
let mut shift_left = self.rightmost;
if h_align == HorizontalAlign::Center {
shift_left /= 2.0;
}
point(screen_position.0 - shift_left, screen_position.1)
}
};
let screen_pos = match v_align {
VerticalAlign::Top => screen_left,
VerticalAlign::Center => {
let mut screen_pos = screen_left;
screen_pos.y -= self.line_height() / 2.0;
screen_pos
}
VerticalAlign::Bottom => {
let mut screen_pos = screen_left;
screen_pos.y -= self.line_height();
screen_pos
}
};
self.glyphs
.iter_mut()
.for_each(|sg| sg.glyph.position += screen_pos);
self.glyphs
}
|
/// `Line` iterator.
///
/// Will iterator through `Word` until the next word would break the `width_bound`.
///
/// Note: Will always have at least one word, if possible, even if the word itself
/// breaks the `width_bound`.
pub(crate) struct Lines<'a, 'b, L, F, S>
where
L: LineBreaker,
F: Font,
S: Iterator<Item = SectionText<'a>>,
{
pub(crate) words: Peekable<Words<'a, 'b, L, F, S>>,
pub(crate) width_bound: f32,
}
impl<'a, L, F, S> Iterator for Lines<'a, '_, L, F, S>
where
L: LineBreaker,
F: Font,
S: Iterator<Item = SectionText<'a>>,
{
type Item = Line;
fn next(&mut self) -> Option<Self::Item> {
let mut caret = point(0.0, 0.0);
let mut line = Line::default();
let mut progressed = false;
while let Some(word) = self.words.peek() {
let word_right = caret.x + word.layout_width_no_trail;
// Reduce float errors by using relative "<= width bound" check
let word_in_bounds =
word_right < self.width_bound || approx::relative_eq!(word_right, self.width_bound);
// only if `progressed` means the first word is allowed to overlap the bounds
if!word_in_bounds && progressed {
break;
}
let word = self.words.next().unwrap();
progressed = true;
line.rightmost = word_right;
if (line.glyphs.is_empty() ||!word.glyphs.is_empty())
&& word.max_v_metrics.height() > line.max_v_metrics.height()
{
let diff_y = word.max_v_metrics.ascent - caret.y;
caret.y += diff_y;
// modify all smaller lined glyphs to occupy the new larger line
for SectionGlyph { glyph,.. } in &mut line.glyphs {
glyph.position.y += diff_y;
}
line.max_v_metrics = word.max_v_metrics;
}
line.glyphs.extend(word.glyphs.into_iter().map(|mut sg| {
sg.glyph.position += caret;
sg
}));
caret.x += word.layout_width;
if word.hard_break {
break;
}
}
Some(line).filter(|_| progressed)
}
}
impl<'a, L, F, S> FusedIterator for Lines<'a, '_, L, F, S>
where
L: LineBreaker,
F: Font,
S: Iterator<Item = SectionText<'a>>,
{
}
|
}
|
random_line_split
|
lines.rs
|
use super::{HorizontalAlign, SectionGlyph, SectionText, VerticalAlign};
use crate::{linebreak::LineBreaker, words::*};
use ab_glyph::*;
use std::iter::{FusedIterator, Iterator, Peekable};
/// A line of `Word`s limited to a max width bound.
#[derive(Default)]
pub(crate) struct Line {
pub glyphs: Vec<SectionGlyph>,
pub max_v_metrics: VMetrics,
pub rightmost: f32,
}
impl Line {
#[inline]
pub(crate) fn line_height(&self) -> f32 {
self.max_v_metrics.ascent - self.max_v_metrics.descent + self.max_v_metrics.line_gap
}
/// Returns line glyphs positioned on the screen and aligned.
pub fn aligned_on_screen(
mut self,
screen_position: (f32, f32),
h_align: HorizontalAlign,
v_align: VerticalAlign,
) -> Vec<SectionGlyph> {
if self.glyphs.is_empty() {
return Vec::new();
}
// implement v-aligns when they're are supported
let screen_left = match h_align {
HorizontalAlign::Left => point(screen_position.0, screen_position.1),
// - Right alignment attained from left by shifting the line
// leftwards by the rightmost x distance from render position
// - Central alignment is attained from left by shifting the line
// leftwards by half the rightmost x distance from render position
HorizontalAlign::Center | HorizontalAlign::Right => {
let mut shift_left = self.rightmost;
if h_align == HorizontalAlign::Center {
shift_left /= 2.0;
}
point(screen_position.0 - shift_left, screen_position.1)
}
};
let screen_pos = match v_align {
VerticalAlign::Top => screen_left,
VerticalAlign::Center => {
let mut screen_pos = screen_left;
screen_pos.y -= self.line_height() / 2.0;
screen_pos
}
VerticalAlign::Bottom => {
let mut screen_pos = screen_left;
screen_pos.y -= self.line_height();
screen_pos
}
};
self.glyphs
.iter_mut()
.for_each(|sg| sg.glyph.position += screen_pos);
self.glyphs
}
}
/// `Line` iterator.
///
/// Will iterator through `Word` until the next word would break the `width_bound`.
///
/// Note: Will always have at least one word, if possible, even if the word itself
/// breaks the `width_bound`.
pub(crate) struct Lines<'a, 'b, L, F, S>
where
L: LineBreaker,
F: Font,
S: Iterator<Item = SectionText<'a>>,
{
pub(crate) words: Peekable<Words<'a, 'b, L, F, S>>,
pub(crate) width_bound: f32,
}
impl<'a, L, F, S> Iterator for Lines<'a, '_, L, F, S>
where
L: LineBreaker,
F: Font,
S: Iterator<Item = SectionText<'a>>,
{
type Item = Line;
fn next(&mut self) -> Option<Self::Item>
|
line.rightmost = word_right;
if (line.glyphs.is_empty() ||!word.glyphs.is_empty())
&& word.max_v_metrics.height() > line.max_v_metrics.height()
{
let diff_y = word.max_v_metrics.ascent - caret.y;
caret.y += diff_y;
// modify all smaller lined glyphs to occupy the new larger line
for SectionGlyph { glyph,.. } in &mut line.glyphs {
glyph.position.y += diff_y;
}
line.max_v_metrics = word.max_v_metrics;
}
line.glyphs.extend(word.glyphs.into_iter().map(|mut sg| {
sg.glyph.position += caret;
sg
}));
caret.x += word.layout_width;
if word.hard_break {
break;
}
}
Some(line).filter(|_| progressed)
}
}
impl<'a, L, F, S> FusedIterator for Lines<'a, '_, L, F, S>
where
L: LineBreaker,
F: Font,
S: Iterator<Item = SectionText<'a>>,
{
}
|
{
let mut caret = point(0.0, 0.0);
let mut line = Line::default();
let mut progressed = false;
while let Some(word) = self.words.peek() {
let word_right = caret.x + word.layout_width_no_trail;
// Reduce float errors by using relative "<= width bound" check
let word_in_bounds =
word_right < self.width_bound || approx::relative_eq!(word_right, self.width_bound);
// only if `progressed` means the first word is allowed to overlap the bounds
if !word_in_bounds && progressed {
break;
}
let word = self.words.next().unwrap();
progressed = true;
|
identifier_body
|
interfaces.rs
|
// Copyright 2020 Google LLC
//
// Use of this source code is governed by an MIT-style license that can be found
// in the LICENSE file or at https://opensource.org/licenses/MIT.
//! A handler and associated types for the interfaces action.
//!
//! The interfaces action lists all network interfaces available on the client,
//! collecting their names, MAC and IP addresses.
use log::error;
use pnet::{
datalink::{self, NetworkInterface},
ipnetwork::IpNetwork,
util::MacAddr,
};
use rrg_proto::{Interface, NetworkAddress};
use crate::session::{self, Session};
/// A response type for the interfaces action.
#[derive(Debug)]
pub struct Response {
/// Information about an interface.
interface: NetworkInterface,
}
/// Handles requests for the interfaces action.
pub fn handle<S: Session>(session: &mut S, _: ()) -> session::Result<()> {
for interface in datalink::interfaces() {
session.reply(Response {
interface: interface,
})?;
}
Ok(())
}
/// Converts a [`MacAddr`][mac_addr] to a vector of bytes,
/// which is what protobuf expects as a MAC.
///
/// [mac_addr]:../../../pnet/util/struct.MacAddr.html
fn mac_to_vec(mac: MacAddr) -> Vec<u8> {
vec![mac.0, mac.1, mac.2, mac.3, mac.4, mac.5]
}
/// Converts a single [`IpNetwork`][ip_network] to a protobuf struct
|
fn ip_to_proto(ip_network: IpNetwork) -> NetworkAddress {
use rrg_proto::network_address::Family;
use std::net::IpAddr::{V4, V6};
match ip_network.ip() {
V4(ipv4) => NetworkAddress {
address_type: Some(Family::Inet.into()),
packed_bytes: Some(ipv4.octets().to_vec()),
..Default::default()
},
V6(ipv6) => NetworkAddress {
address_type: Some(Family::Inet6.into()),
packed_bytes: Some(ipv6.octets().to_vec()),
..Default::default()
},
}
}
/// Maps a vector of [`IpNetwork`][ip_network]s to a vector
/// of protobuf structs corresponding to an IP address.
///
/// [ip_network]:../../../ipnetwork/enum.IpNetwork.html
fn ips_to_protos(ips: Vec<IpNetwork>) -> Vec<NetworkAddress> {
ips.into_iter().map(ip_to_proto).collect()
}
impl super::Response for Response {
const RDF_NAME: Option<&'static str> = Some("Interface");
type Proto = Interface;
fn into_proto(self) -> Interface {
let mac = match self.interface.mac {
Some(mac) => Some(mac_to_vec(mac)),
None => {
error!(
"unable to get MAC address for {} interface",
self.interface.name,
);
None
},
};
Interface {
mac_address: mac,
ifname: Some(self.interface.name),
addresses: ips_to_protos(self.interface.ips),
..Default::default()
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_loopback_presence() {
let mut session = session::test::Fake::new();
assert!(handle(&mut session, ()).is_ok());
let mut is_loopback_present = false;
for i in 0..session.reply_count() {
let interface = &session.reply::<Response>(i).interface;
is_loopback_present |= interface.is_loopback();
}
assert!(is_loopback_present);
}
}
|
/// corresponding to an IP address.
///
/// [ip_network]: ../../../ipnetwork/enum.IpNetwork.html
|
random_line_split
|
interfaces.rs
|
// Copyright 2020 Google LLC
//
// Use of this source code is governed by an MIT-style license that can be found
// in the LICENSE file or at https://opensource.org/licenses/MIT.
//! A handler and associated types for the interfaces action.
//!
//! The interfaces action lists all network interfaces available on the client,
//! collecting their names, MAC and IP addresses.
use log::error;
use pnet::{
datalink::{self, NetworkInterface},
ipnetwork::IpNetwork,
util::MacAddr,
};
use rrg_proto::{Interface, NetworkAddress};
use crate::session::{self, Session};
/// A response type for the interfaces action.
#[derive(Debug)]
pub struct Response {
/// Information about an interface.
interface: NetworkInterface,
}
/// Handles requests for the interfaces action.
pub fn handle<S: Session>(session: &mut S, _: ()) -> session::Result<()> {
for interface in datalink::interfaces() {
session.reply(Response {
interface: interface,
})?;
}
Ok(())
}
/// Converts a [`MacAddr`][mac_addr] to a vector of bytes,
/// which is what protobuf expects as a MAC.
///
/// [mac_addr]:../../../pnet/util/struct.MacAddr.html
fn mac_to_vec(mac: MacAddr) -> Vec<u8> {
vec![mac.0, mac.1, mac.2, mac.3, mac.4, mac.5]
}
/// Converts a single [`IpNetwork`][ip_network] to a protobuf struct
/// corresponding to an IP address.
///
/// [ip_network]:../../../ipnetwork/enum.IpNetwork.html
fn ip_to_proto(ip_network: IpNetwork) -> NetworkAddress {
use rrg_proto::network_address::Family;
use std::net::IpAddr::{V4, V6};
match ip_network.ip() {
V4(ipv4) => NetworkAddress {
address_type: Some(Family::Inet.into()),
packed_bytes: Some(ipv4.octets().to_vec()),
..Default::default()
},
V6(ipv6) => NetworkAddress {
address_type: Some(Family::Inet6.into()),
packed_bytes: Some(ipv6.octets().to_vec()),
..Default::default()
},
}
}
/// Maps a vector of [`IpNetwork`][ip_network]s to a vector
/// of protobuf structs corresponding to an IP address.
///
/// [ip_network]:../../../ipnetwork/enum.IpNetwork.html
fn
|
(ips: Vec<IpNetwork>) -> Vec<NetworkAddress> {
ips.into_iter().map(ip_to_proto).collect()
}
impl super::Response for Response {
const RDF_NAME: Option<&'static str> = Some("Interface");
type Proto = Interface;
fn into_proto(self) -> Interface {
let mac = match self.interface.mac {
Some(mac) => Some(mac_to_vec(mac)),
None => {
error!(
"unable to get MAC address for {} interface",
self.interface.name,
);
None
},
};
Interface {
mac_address: mac,
ifname: Some(self.interface.name),
addresses: ips_to_protos(self.interface.ips),
..Default::default()
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_loopback_presence() {
let mut session = session::test::Fake::new();
assert!(handle(&mut session, ()).is_ok());
let mut is_loopback_present = false;
for i in 0..session.reply_count() {
let interface = &session.reply::<Response>(i).interface;
is_loopback_present |= interface.is_loopback();
}
assert!(is_loopback_present);
}
}
|
ips_to_protos
|
identifier_name
|
interfaces.rs
|
// Copyright 2020 Google LLC
//
// Use of this source code is governed by an MIT-style license that can be found
// in the LICENSE file or at https://opensource.org/licenses/MIT.
//! A handler and associated types for the interfaces action.
//!
//! The interfaces action lists all network interfaces available on the client,
//! collecting their names, MAC and IP addresses.
use log::error;
use pnet::{
datalink::{self, NetworkInterface},
ipnetwork::IpNetwork,
util::MacAddr,
};
use rrg_proto::{Interface, NetworkAddress};
use crate::session::{self, Session};
/// A response type for the interfaces action.
#[derive(Debug)]
pub struct Response {
/// Information about an interface.
interface: NetworkInterface,
}
/// Handles requests for the interfaces action.
pub fn handle<S: Session>(session: &mut S, _: ()) -> session::Result<()> {
for interface in datalink::interfaces() {
session.reply(Response {
interface: interface,
})?;
}
Ok(())
}
/// Converts a [`MacAddr`][mac_addr] to a vector of bytes,
/// which is what protobuf expects as a MAC.
///
/// [mac_addr]:../../../pnet/util/struct.MacAddr.html
fn mac_to_vec(mac: MacAddr) -> Vec<u8> {
vec![mac.0, mac.1, mac.2, mac.3, mac.4, mac.5]
}
/// Converts a single [`IpNetwork`][ip_network] to a protobuf struct
/// corresponding to an IP address.
///
/// [ip_network]:../../../ipnetwork/enum.IpNetwork.html
fn ip_to_proto(ip_network: IpNetwork) -> NetworkAddress {
use rrg_proto::network_address::Family;
use std::net::IpAddr::{V4, V6};
match ip_network.ip() {
V4(ipv4) => NetworkAddress {
address_type: Some(Family::Inet.into()),
packed_bytes: Some(ipv4.octets().to_vec()),
..Default::default()
},
V6(ipv6) => NetworkAddress {
address_type: Some(Family::Inet6.into()),
packed_bytes: Some(ipv6.octets().to_vec()),
..Default::default()
},
}
}
/// Maps a vector of [`IpNetwork`][ip_network]s to a vector
/// of protobuf structs corresponding to an IP address.
///
/// [ip_network]:../../../ipnetwork/enum.IpNetwork.html
fn ips_to_protos(ips: Vec<IpNetwork>) -> Vec<NetworkAddress>
|
impl super::Response for Response {
const RDF_NAME: Option<&'static str> = Some("Interface");
type Proto = Interface;
fn into_proto(self) -> Interface {
let mac = match self.interface.mac {
Some(mac) => Some(mac_to_vec(mac)),
None => {
error!(
"unable to get MAC address for {} interface",
self.interface.name,
);
None
},
};
Interface {
mac_address: mac,
ifname: Some(self.interface.name),
addresses: ips_to_protos(self.interface.ips),
..Default::default()
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_loopback_presence() {
let mut session = session::test::Fake::new();
assert!(handle(&mut session, ()).is_ok());
let mut is_loopback_present = false;
for i in 0..session.reply_count() {
let interface = &session.reply::<Response>(i).interface;
is_loopback_present |= interface.is_loopback();
}
assert!(is_loopback_present);
}
}
|
{
ips.into_iter().map(ip_to_proto).collect()
}
|
identifier_body
|
htmlpreelement.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/. */
use dom::bindings::codegen::Bindings::HTMLPreElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLPreElementDerived;
use dom::bindings::js::Root;
use dom::document::Document;
use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::element::ElementTypeId;
use dom::htmlelement::{HTMLElement, HTMLElementTypeId};
use dom::node::{Node, NodeTypeId};
use util::str::DOMString;
#[dom_struct]
#[derive(HeapSizeOf)]
pub struct HTMLPreElement {
htmlelement: HTMLElement,
}
impl HTMLPreElementDerived for EventTarget {
fn is_htmlpreelement(&self) -> bool
|
}
impl HTMLPreElement {
fn new_inherited(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> HTMLPreElement {
HTMLPreElement {
htmlelement:
HTMLElement::new_inherited(HTMLElementTypeId::HTMLPreElement, localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLPreElement> {
let element = HTMLPreElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLPreElementBinding::Wrap)
}
}
|
{
*self.type_id() ==
EventTargetTypeId::Node(
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLPreElement)))
}
|
identifier_body
|
htmlpreelement.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/. */
|
use dom::bindings::codegen::Bindings::HTMLPreElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLPreElementDerived;
use dom::bindings::js::Root;
use dom::document::Document;
use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::element::ElementTypeId;
use dom::htmlelement::{HTMLElement, HTMLElementTypeId};
use dom::node::{Node, NodeTypeId};
use util::str::DOMString;
#[dom_struct]
#[derive(HeapSizeOf)]
pub struct HTMLPreElement {
htmlelement: HTMLElement,
}
impl HTMLPreElementDerived for EventTarget {
fn is_htmlpreelement(&self) -> bool {
*self.type_id() ==
EventTargetTypeId::Node(
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLPreElement)))
}
}
impl HTMLPreElement {
fn new_inherited(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> HTMLPreElement {
HTMLPreElement {
htmlelement:
HTMLElement::new_inherited(HTMLElementTypeId::HTMLPreElement, localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLPreElement> {
let element = HTMLPreElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLPreElementBinding::Wrap)
}
}
|
random_line_split
|
|
htmlpreelement.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/. */
use dom::bindings::codegen::Bindings::HTMLPreElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLPreElementDerived;
use dom::bindings::js::Root;
use dom::document::Document;
use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::element::ElementTypeId;
use dom::htmlelement::{HTMLElement, HTMLElementTypeId};
use dom::node::{Node, NodeTypeId};
use util::str::DOMString;
#[dom_struct]
#[derive(HeapSizeOf)]
pub struct HTMLPreElement {
htmlelement: HTMLElement,
}
impl HTMLPreElementDerived for EventTarget {
fn is_htmlpreelement(&self) -> bool {
*self.type_id() ==
EventTargetTypeId::Node(
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLPreElement)))
}
}
impl HTMLPreElement {
fn new_inherited(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> HTMLPreElement {
HTMLPreElement {
htmlelement:
HTMLElement::new_inherited(HTMLElementTypeId::HTMLPreElement, localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn
|
(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLPreElement> {
let element = HTMLPreElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLPreElementBinding::Wrap)
}
}
|
new
|
identifier_name
|
close.rs
|
use futures_core::future::Future;
use futures_core::task::{Context, Poll};
use futures_io::AsyncWrite;
use std::io;
use std::pin::Pin;
/// Future for the [`close`](super::AsyncWriteExt::close) method.
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct Close<'a, W:?Sized> {
writer: &'a mut W,
}
impl<W:?Sized + Unpin> Unpin for Close<'_, W> {}
impl<'a, W: AsyncWrite +?Sized + Unpin> Close<'a, W> {
pub(super) fn new(writer: &'a mut W) -> Self
|
}
impl<W: AsyncWrite +?Sized + Unpin> Future for Close<'_, W> {
type Output = io::Result<()>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
Pin::new(&mut *self.writer).poll_close(cx)
}
}
|
{
Close { writer }
}
|
identifier_body
|
close.rs
|
use futures_core::future::Future;
use futures_core::task::{Context, Poll};
use futures_io::AsyncWrite;
use std::io;
use std::pin::Pin;
/// Future for the [`close`](super::AsyncWriteExt::close) method.
#[derive(Debug)]
|
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct Close<'a, W:?Sized> {
writer: &'a mut W,
}
impl<W:?Sized + Unpin> Unpin for Close<'_, W> {}
impl<'a, W: AsyncWrite +?Sized + Unpin> Close<'a, W> {
pub(super) fn new(writer: &'a mut W) -> Self {
Close { writer }
}
}
impl<W: AsyncWrite +?Sized + Unpin> Future for Close<'_, W> {
type Output = io::Result<()>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
Pin::new(&mut *self.writer).poll_close(cx)
}
}
|
random_line_split
|
|
close.rs
|
use futures_core::future::Future;
use futures_core::task::{Context, Poll};
use futures_io::AsyncWrite;
use std::io;
use std::pin::Pin;
/// Future for the [`close`](super::AsyncWriteExt::close) method.
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct
|
<'a, W:?Sized> {
writer: &'a mut W,
}
impl<W:?Sized + Unpin> Unpin for Close<'_, W> {}
impl<'a, W: AsyncWrite +?Sized + Unpin> Close<'a, W> {
pub(super) fn new(writer: &'a mut W) -> Self {
Close { writer }
}
}
impl<W: AsyncWrite +?Sized + Unpin> Future for Close<'_, W> {
type Output = io::Result<()>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
Pin::new(&mut *self.writer).poll_close(cx)
}
}
|
Close
|
identifier_name
|
mod.rs
|
extern crate android_glue;
use libc;
use std::ffi::{CString};
use std::sync::mpsc::{Receiver, channel};
use {CreationError, Event, MouseCursor};
use CreationError::OsError;
use events::ElementState::{Pressed, Released};
use events::Event::{MouseInput, MouseMoved};
use events::MouseButton;
use std::collections::VecDeque;
use Api;
use BuilderAttribs;
use GlRequest;
pub struct Window {
display: ffi::egl::types::EGLDisplay,
context: ffi::egl::types::EGLContext,
surface: ffi::egl::types::EGLSurface,
event_rx: Receiver<android_glue::Event>,
}
pub struct MonitorID;
mod ffi;
pub fn get_available_monitors() -> VecDeque <MonitorID> {
let mut rb = VecDeque::new();
rb.push_back(MonitorID);
rb
}
pub fn get_primary_monitor() -> MonitorID {
MonitorID
}
impl MonitorID {
pub fn get_name(&self) -> Option<String> {
Some("Primary".to_string())
}
pub fn get_dimensions(&self) -> (u32, u32) {
unimplemented!()
}
}
#[cfg(feature = "headless")]
pub struct HeadlessContext(i32);
#[cfg(feature = "headless")]
impl HeadlessContext {
/// See the docs in the crate root file.
pub fn new(_builder: BuilderAttribs) -> Result<HeadlessContext, CreationError> {
unimplemented!()
}
/// See the docs in the crate root file.
pub unsafe fn make_current(&self) {
unimplemented!()
}
/// See the docs in the crate root file.
pub fn is_current(&self) -> bool {
unimplemented!()
}
/// See the docs in the crate root file.
pub fn get_proc_address(&self, _addr: &str) -> *const () {
unimplemented!()
}
pub fn get_api(&self) -> ::Api {
::Api::OpenGlEs
}
}
#[cfg(feature = "headless")]
unsafe impl Send for HeadlessContext {}
#[cfg(feature = "headless")]
unsafe impl Sync for HeadlessContext {}
pub struct PollEventsIterator<'a> {
window: &'a Window,
}
impl<'a> Iterator for PollEventsIterator<'a> {
type Item = Event;
fn next(&mut self) -> Option<Event> {
match self.window.event_rx.try_recv() {
Ok(event) => {
match event {
android_glue::Event::EventDown => Some(MouseInput(Pressed, MouseButton::Left)),
android_glue::Event::EventUp => Some(MouseInput(Released, MouseButton::Left)),
android_glue::Event::EventMove(x, y) => Some(MouseMoved((x as i32, y as i32))),
_ => None,
}
}
Err(_) => {
None
}
}
}
}
pub struct WaitEventsIterator<'a> {
window: &'a Window,
}
impl<'a> Iterator for WaitEventsIterator<'a> {
type Item = Event;
fn next(&mut self) -> Option<Event> {
use std::time::Duration;
use std::old_io::timer;
loop {
// calling poll_events()
if let Some(ev) = self.window.poll_events().next() {
return Some(ev);
}
// TODO: Implement a proper way of sleeping on the event queue
timer::sleep(Duration::milliseconds(16));
}
}
}
impl Window {
pub fn new(builder: BuilderAttribs) -> Result<Window, CreationError> {
use std::{mem, ptr};
if builder.sharing.is_some() {
unimplemented!()
}
let native_window = unsafe { android_glue::get_native_window() };
if native_window.is_null() {
return Err(OsError(format!("Android's native window is null")));
}
let display = unsafe {
let display = ffi::egl::GetDisplay(mem::transmute(ffi::egl::DEFAULT_DISPLAY));
if display.is_null() {
return Err(OsError("No EGL display connection available".to_string()));
}
display
};
android_glue::write_log("eglGetDisplay succeeded");
let (_major, _minor) = unsafe {
let mut major: ffi::egl::types::EGLint = mem::uninitialized();
let mut minor: ffi::egl::types::EGLint = mem::uninitialized();
if ffi::egl::Initialize(display, &mut major, &mut minor) == 0
|
(major, minor)
};
android_glue::write_log("eglInitialize succeeded");
let use_gles2 = match builder.gl_version {
GlRequest::Specific(Api::OpenGlEs, (2, _)) => true,
GlRequest::Specific(Api::OpenGlEs, _) => false,
GlRequest::Specific(_, _) => panic!("Only OpenGL ES is supported"), // FIXME: return a result
GlRequest::GlThenGles { opengles_version: (2, _),.. } => true,
_ => false,
};
let mut attribute_list = vec!();
if use_gles2 {
attribute_list.push_all(&[
ffi::egl::RENDERABLE_TYPE as i32,
ffi::egl::OPENGL_ES2_BIT as i32,
]);
}
{
let (red, green, blue) = match builder.color_bits.unwrap_or(24) {
24 => (8, 8, 8),
16 => (6, 5, 6),
_ => panic!("Bad color_bits"),
};
attribute_list.push_all(&[ffi::egl::RED_SIZE as i32, red]);
attribute_list.push_all(&[ffi::egl::GREEN_SIZE as i32, green]);
attribute_list.push_all(&[ffi::egl::BLUE_SIZE as i32, blue]);
}
attribute_list.push_all(&[
ffi::egl::DEPTH_SIZE as i32,
builder.depth_bits.unwrap_or(8) as i32,
]);
attribute_list.push(ffi::egl::NONE as i32);
let config = unsafe {
let mut num_config: ffi::egl::types::EGLint = mem::uninitialized();
let mut config: ffi::egl::types::EGLConfig = mem::uninitialized();
if ffi::egl::ChooseConfig(display, attribute_list.as_ptr(), &mut config, 1,
&mut num_config) == 0
{
return Err(OsError(format!("eglChooseConfig failed")))
}
if num_config <= 0 {
return Err(OsError(format!("eglChooseConfig returned no available config")))
}
config
};
android_glue::write_log("eglChooseConfig succeeded");
let context = unsafe {
let mut context_attributes = vec!();
if use_gles2 {
context_attributes.push_all(&[ffi::egl::CONTEXT_CLIENT_VERSION as i32, 2]);
}
context_attributes.push(ffi::egl::NONE as i32);
let context = ffi::egl::CreateContext(display, config, ptr::null(),
context_attributes.as_ptr());
if context.is_null() {
return Err(OsError(format!("eglCreateContext failed")))
}
context
};
android_glue::write_log("eglCreateContext succeeded");
let surface = unsafe {
let surface = ffi::egl::CreateWindowSurface(display, config, native_window, ptr::null());
if surface.is_null() {
return Err(OsError(format!("eglCreateWindowSurface failed")))
}
surface
};
android_glue::write_log("eglCreateWindowSurface succeeded");
let (tx, rx) = channel();
android_glue::add_sender(tx);
Ok(Window {
display: display,
context: context,
surface: surface,
event_rx: rx,
})
}
pub fn is_closed(&self) -> bool {
false
}
pub fn set_title(&self, _: &str) {
}
pub fn show(&self) {
}
pub fn hide(&self) {
}
pub fn get_position(&self) -> Option<(i32, i32)> {
None
}
pub fn set_position(&self, _x: i32, _y: i32) {
}
pub fn get_inner_size(&self) -> Option<(u32, u32)> {
let native_window = unsafe { android_glue::get_native_window() };
if native_window.is_null() {
None
} else {
Some((
unsafe { ffi::ANativeWindow_getWidth(native_window) } as u32,
unsafe { ffi::ANativeWindow_getHeight(native_window) } as u32
))
}
}
pub fn get_outer_size(&self) -> Option<(u32, u32)> {
self.get_inner_size()
}
pub fn set_inner_size(&self, _x: u32, _y: u32) {
}
pub fn create_window_proxy(&self) -> WindowProxy {
WindowProxy
}
pub fn poll_events(&self) -> PollEventsIterator {
PollEventsIterator {
window: self
}
}
pub fn wait_events(&self) -> WaitEventsIterator {
WaitEventsIterator {
window: self
}
}
pub fn make_current(&self) {
unsafe {
ffi::egl::MakeCurrent(self.display, self.surface, self.surface, self.context);
}
}
pub fn is_current(&self) -> bool {
unsafe { ffi::egl::GetCurrentContext() == self.context }
}
pub fn get_proc_address(&self, addr: &str) -> *const () {
let addr = CString::from_slice(addr.as_bytes());
let addr = addr.as_ptr();
unsafe {
ffi::egl::GetProcAddress(addr) as *const ()
}
}
pub fn swap_buffers(&self) {
unsafe {
ffi::egl::SwapBuffers(self.display, self.surface);
}
}
pub fn platform_display(&self) -> *mut libc::c_void {
self.display as *mut libc::c_void
}
pub fn platform_window(&self) -> *mut libc::c_void {
unimplemented!()
}
pub fn get_api(&self) -> ::Api {
::Api::OpenGlEs
}
pub fn set_window_resize_callback(&mut self, _: Option<fn(u32, u32)>) {
}
pub fn set_cursor(&self, _: MouseCursor) {
}
pub fn hidpi_factor(&self) -> f32 {
1.0
}
pub fn set_cursor_position(&self, x: i32, y: i32) -> Result<(), ()> {
unimplemented!();
}
}
unsafe impl Send for Window {}
unsafe impl Sync for Window {}
#[cfg(feature = "window")]
#[derive(Clone)]
pub struct WindowProxy;
impl WindowProxy {
pub fn wakeup_event_loop(&self) {
unimplemented!()
}
}
#[unsafe_destructor]
impl Drop for Window {
fn drop(&mut self) {
use std::ptr;
unsafe {
// we don't call MakeCurrent(0, 0) because we are not sure that the context
// is still the current one
android_glue::write_log("Destroying gl-init window");
ffi::egl::DestroySurface(self.display, self.surface);
ffi::egl::DestroyContext(self.display, self.context);
ffi::egl::Terminate(self.display);
}
}
}
|
{
return Err(OsError(format!("eglInitialize failed")))
}
|
conditional_block
|
mod.rs
|
extern crate android_glue;
use libc;
use std::ffi::{CString};
use std::sync::mpsc::{Receiver, channel};
use {CreationError, Event, MouseCursor};
use CreationError::OsError;
use events::ElementState::{Pressed, Released};
use events::Event::{MouseInput, MouseMoved};
use events::MouseButton;
use std::collections::VecDeque;
use Api;
use BuilderAttribs;
use GlRequest;
pub struct Window {
display: ffi::egl::types::EGLDisplay,
context: ffi::egl::types::EGLContext,
surface: ffi::egl::types::EGLSurface,
event_rx: Receiver<android_glue::Event>,
}
pub struct MonitorID;
mod ffi;
pub fn get_available_monitors() -> VecDeque <MonitorID> {
let mut rb = VecDeque::new();
rb.push_back(MonitorID);
rb
}
pub fn get_primary_monitor() -> MonitorID {
MonitorID
}
impl MonitorID {
pub fn get_name(&self) -> Option<String> {
Some("Primary".to_string())
}
pub fn get_dimensions(&self) -> (u32, u32)
|
}
#[cfg(feature = "headless")]
pub struct HeadlessContext(i32);
#[cfg(feature = "headless")]
impl HeadlessContext {
/// See the docs in the crate root file.
pub fn new(_builder: BuilderAttribs) -> Result<HeadlessContext, CreationError> {
unimplemented!()
}
/// See the docs in the crate root file.
pub unsafe fn make_current(&self) {
unimplemented!()
}
/// See the docs in the crate root file.
pub fn is_current(&self) -> bool {
unimplemented!()
}
/// See the docs in the crate root file.
pub fn get_proc_address(&self, _addr: &str) -> *const () {
unimplemented!()
}
pub fn get_api(&self) -> ::Api {
::Api::OpenGlEs
}
}
#[cfg(feature = "headless")]
unsafe impl Send for HeadlessContext {}
#[cfg(feature = "headless")]
unsafe impl Sync for HeadlessContext {}
pub struct PollEventsIterator<'a> {
window: &'a Window,
}
impl<'a> Iterator for PollEventsIterator<'a> {
type Item = Event;
fn next(&mut self) -> Option<Event> {
match self.window.event_rx.try_recv() {
Ok(event) => {
match event {
android_glue::Event::EventDown => Some(MouseInput(Pressed, MouseButton::Left)),
android_glue::Event::EventUp => Some(MouseInput(Released, MouseButton::Left)),
android_glue::Event::EventMove(x, y) => Some(MouseMoved((x as i32, y as i32))),
_ => None,
}
}
Err(_) => {
None
}
}
}
}
pub struct WaitEventsIterator<'a> {
window: &'a Window,
}
impl<'a> Iterator for WaitEventsIterator<'a> {
type Item = Event;
fn next(&mut self) -> Option<Event> {
use std::time::Duration;
use std::old_io::timer;
loop {
// calling poll_events()
if let Some(ev) = self.window.poll_events().next() {
return Some(ev);
}
// TODO: Implement a proper way of sleeping on the event queue
timer::sleep(Duration::milliseconds(16));
}
}
}
impl Window {
pub fn new(builder: BuilderAttribs) -> Result<Window, CreationError> {
use std::{mem, ptr};
if builder.sharing.is_some() {
unimplemented!()
}
let native_window = unsafe { android_glue::get_native_window() };
if native_window.is_null() {
return Err(OsError(format!("Android's native window is null")));
}
let display = unsafe {
let display = ffi::egl::GetDisplay(mem::transmute(ffi::egl::DEFAULT_DISPLAY));
if display.is_null() {
return Err(OsError("No EGL display connection available".to_string()));
}
display
};
android_glue::write_log("eglGetDisplay succeeded");
let (_major, _minor) = unsafe {
let mut major: ffi::egl::types::EGLint = mem::uninitialized();
let mut minor: ffi::egl::types::EGLint = mem::uninitialized();
if ffi::egl::Initialize(display, &mut major, &mut minor) == 0 {
return Err(OsError(format!("eglInitialize failed")))
}
(major, minor)
};
android_glue::write_log("eglInitialize succeeded");
let use_gles2 = match builder.gl_version {
GlRequest::Specific(Api::OpenGlEs, (2, _)) => true,
GlRequest::Specific(Api::OpenGlEs, _) => false,
GlRequest::Specific(_, _) => panic!("Only OpenGL ES is supported"), // FIXME: return a result
GlRequest::GlThenGles { opengles_version: (2, _),.. } => true,
_ => false,
};
let mut attribute_list = vec!();
if use_gles2 {
attribute_list.push_all(&[
ffi::egl::RENDERABLE_TYPE as i32,
ffi::egl::OPENGL_ES2_BIT as i32,
]);
}
{
let (red, green, blue) = match builder.color_bits.unwrap_or(24) {
24 => (8, 8, 8),
16 => (6, 5, 6),
_ => panic!("Bad color_bits"),
};
attribute_list.push_all(&[ffi::egl::RED_SIZE as i32, red]);
attribute_list.push_all(&[ffi::egl::GREEN_SIZE as i32, green]);
attribute_list.push_all(&[ffi::egl::BLUE_SIZE as i32, blue]);
}
attribute_list.push_all(&[
ffi::egl::DEPTH_SIZE as i32,
builder.depth_bits.unwrap_or(8) as i32,
]);
attribute_list.push(ffi::egl::NONE as i32);
let config = unsafe {
let mut num_config: ffi::egl::types::EGLint = mem::uninitialized();
let mut config: ffi::egl::types::EGLConfig = mem::uninitialized();
if ffi::egl::ChooseConfig(display, attribute_list.as_ptr(), &mut config, 1,
&mut num_config) == 0
{
return Err(OsError(format!("eglChooseConfig failed")))
}
if num_config <= 0 {
return Err(OsError(format!("eglChooseConfig returned no available config")))
}
config
};
android_glue::write_log("eglChooseConfig succeeded");
let context = unsafe {
let mut context_attributes = vec!();
if use_gles2 {
context_attributes.push_all(&[ffi::egl::CONTEXT_CLIENT_VERSION as i32, 2]);
}
context_attributes.push(ffi::egl::NONE as i32);
let context = ffi::egl::CreateContext(display, config, ptr::null(),
context_attributes.as_ptr());
if context.is_null() {
return Err(OsError(format!("eglCreateContext failed")))
}
context
};
android_glue::write_log("eglCreateContext succeeded");
let surface = unsafe {
let surface = ffi::egl::CreateWindowSurface(display, config, native_window, ptr::null());
if surface.is_null() {
return Err(OsError(format!("eglCreateWindowSurface failed")))
}
surface
};
android_glue::write_log("eglCreateWindowSurface succeeded");
let (tx, rx) = channel();
android_glue::add_sender(tx);
Ok(Window {
display: display,
context: context,
surface: surface,
event_rx: rx,
})
}
pub fn is_closed(&self) -> bool {
false
}
pub fn set_title(&self, _: &str) {
}
pub fn show(&self) {
}
pub fn hide(&self) {
}
pub fn get_position(&self) -> Option<(i32, i32)> {
None
}
pub fn set_position(&self, _x: i32, _y: i32) {
}
pub fn get_inner_size(&self) -> Option<(u32, u32)> {
let native_window = unsafe { android_glue::get_native_window() };
if native_window.is_null() {
None
} else {
Some((
unsafe { ffi::ANativeWindow_getWidth(native_window) } as u32,
unsafe { ffi::ANativeWindow_getHeight(native_window) } as u32
))
}
}
pub fn get_outer_size(&self) -> Option<(u32, u32)> {
self.get_inner_size()
}
pub fn set_inner_size(&self, _x: u32, _y: u32) {
}
pub fn create_window_proxy(&self) -> WindowProxy {
WindowProxy
}
pub fn poll_events(&self) -> PollEventsIterator {
PollEventsIterator {
window: self
}
}
pub fn wait_events(&self) -> WaitEventsIterator {
WaitEventsIterator {
window: self
}
}
pub fn make_current(&self) {
unsafe {
ffi::egl::MakeCurrent(self.display, self.surface, self.surface, self.context);
}
}
pub fn is_current(&self) -> bool {
unsafe { ffi::egl::GetCurrentContext() == self.context }
}
pub fn get_proc_address(&self, addr: &str) -> *const () {
let addr = CString::from_slice(addr.as_bytes());
let addr = addr.as_ptr();
unsafe {
ffi::egl::GetProcAddress(addr) as *const ()
}
}
pub fn swap_buffers(&self) {
unsafe {
ffi::egl::SwapBuffers(self.display, self.surface);
}
}
pub fn platform_display(&self) -> *mut libc::c_void {
self.display as *mut libc::c_void
}
pub fn platform_window(&self) -> *mut libc::c_void {
unimplemented!()
}
pub fn get_api(&self) -> ::Api {
::Api::OpenGlEs
}
pub fn set_window_resize_callback(&mut self, _: Option<fn(u32, u32)>) {
}
pub fn set_cursor(&self, _: MouseCursor) {
}
pub fn hidpi_factor(&self) -> f32 {
1.0
}
pub fn set_cursor_position(&self, x: i32, y: i32) -> Result<(), ()> {
unimplemented!();
}
}
unsafe impl Send for Window {}
unsafe impl Sync for Window {}
#[cfg(feature = "window")]
#[derive(Clone)]
pub struct WindowProxy;
impl WindowProxy {
pub fn wakeup_event_loop(&self) {
unimplemented!()
}
}
#[unsafe_destructor]
impl Drop for Window {
fn drop(&mut self) {
use std::ptr;
unsafe {
// we don't call MakeCurrent(0, 0) because we are not sure that the context
// is still the current one
android_glue::write_log("Destroying gl-init window");
ffi::egl::DestroySurface(self.display, self.surface);
ffi::egl::DestroyContext(self.display, self.context);
ffi::egl::Terminate(self.display);
}
}
}
|
{
unimplemented!()
}
|
identifier_body
|
mod.rs
|
extern crate android_glue;
use libc;
use std::ffi::{CString};
use std::sync::mpsc::{Receiver, channel};
use {CreationError, Event, MouseCursor};
use CreationError::OsError;
use events::ElementState::{Pressed, Released};
use events::Event::{MouseInput, MouseMoved};
use events::MouseButton;
use std::collections::VecDeque;
use Api;
use BuilderAttribs;
use GlRequest;
pub struct Window {
display: ffi::egl::types::EGLDisplay,
context: ffi::egl::types::EGLContext,
surface: ffi::egl::types::EGLSurface,
event_rx: Receiver<android_glue::Event>,
}
pub struct MonitorID;
mod ffi;
pub fn get_available_monitors() -> VecDeque <MonitorID> {
let mut rb = VecDeque::new();
rb.push_back(MonitorID);
rb
}
pub fn get_primary_monitor() -> MonitorID {
MonitorID
}
impl MonitorID {
pub fn get_name(&self) -> Option<String> {
Some("Primary".to_string())
}
pub fn get_dimensions(&self) -> (u32, u32) {
unimplemented!()
}
}
#[cfg(feature = "headless")]
pub struct HeadlessContext(i32);
#[cfg(feature = "headless")]
impl HeadlessContext {
/// See the docs in the crate root file.
pub fn new(_builder: BuilderAttribs) -> Result<HeadlessContext, CreationError> {
unimplemented!()
}
/// See the docs in the crate root file.
pub unsafe fn make_current(&self) {
unimplemented!()
}
/// See the docs in the crate root file.
pub fn is_current(&self) -> bool {
unimplemented!()
}
/// See the docs in the crate root file.
pub fn get_proc_address(&self, _addr: &str) -> *const () {
unimplemented!()
}
pub fn get_api(&self) -> ::Api {
::Api::OpenGlEs
}
}
#[cfg(feature = "headless")]
unsafe impl Send for HeadlessContext {}
#[cfg(feature = "headless")]
unsafe impl Sync for HeadlessContext {}
pub struct
|
<'a> {
window: &'a Window,
}
impl<'a> Iterator for PollEventsIterator<'a> {
type Item = Event;
fn next(&mut self) -> Option<Event> {
match self.window.event_rx.try_recv() {
Ok(event) => {
match event {
android_glue::Event::EventDown => Some(MouseInput(Pressed, MouseButton::Left)),
android_glue::Event::EventUp => Some(MouseInput(Released, MouseButton::Left)),
android_glue::Event::EventMove(x, y) => Some(MouseMoved((x as i32, y as i32))),
_ => None,
}
}
Err(_) => {
None
}
}
}
}
pub struct WaitEventsIterator<'a> {
window: &'a Window,
}
impl<'a> Iterator for WaitEventsIterator<'a> {
type Item = Event;
fn next(&mut self) -> Option<Event> {
use std::time::Duration;
use std::old_io::timer;
loop {
// calling poll_events()
if let Some(ev) = self.window.poll_events().next() {
return Some(ev);
}
// TODO: Implement a proper way of sleeping on the event queue
timer::sleep(Duration::milliseconds(16));
}
}
}
impl Window {
pub fn new(builder: BuilderAttribs) -> Result<Window, CreationError> {
use std::{mem, ptr};
if builder.sharing.is_some() {
unimplemented!()
}
let native_window = unsafe { android_glue::get_native_window() };
if native_window.is_null() {
return Err(OsError(format!("Android's native window is null")));
}
let display = unsafe {
let display = ffi::egl::GetDisplay(mem::transmute(ffi::egl::DEFAULT_DISPLAY));
if display.is_null() {
return Err(OsError("No EGL display connection available".to_string()));
}
display
};
android_glue::write_log("eglGetDisplay succeeded");
let (_major, _minor) = unsafe {
let mut major: ffi::egl::types::EGLint = mem::uninitialized();
let mut minor: ffi::egl::types::EGLint = mem::uninitialized();
if ffi::egl::Initialize(display, &mut major, &mut minor) == 0 {
return Err(OsError(format!("eglInitialize failed")))
}
(major, minor)
};
android_glue::write_log("eglInitialize succeeded");
let use_gles2 = match builder.gl_version {
GlRequest::Specific(Api::OpenGlEs, (2, _)) => true,
GlRequest::Specific(Api::OpenGlEs, _) => false,
GlRequest::Specific(_, _) => panic!("Only OpenGL ES is supported"), // FIXME: return a result
GlRequest::GlThenGles { opengles_version: (2, _),.. } => true,
_ => false,
};
let mut attribute_list = vec!();
if use_gles2 {
attribute_list.push_all(&[
ffi::egl::RENDERABLE_TYPE as i32,
ffi::egl::OPENGL_ES2_BIT as i32,
]);
}
{
let (red, green, blue) = match builder.color_bits.unwrap_or(24) {
24 => (8, 8, 8),
16 => (6, 5, 6),
_ => panic!("Bad color_bits"),
};
attribute_list.push_all(&[ffi::egl::RED_SIZE as i32, red]);
attribute_list.push_all(&[ffi::egl::GREEN_SIZE as i32, green]);
attribute_list.push_all(&[ffi::egl::BLUE_SIZE as i32, blue]);
}
attribute_list.push_all(&[
ffi::egl::DEPTH_SIZE as i32,
builder.depth_bits.unwrap_or(8) as i32,
]);
attribute_list.push(ffi::egl::NONE as i32);
let config = unsafe {
let mut num_config: ffi::egl::types::EGLint = mem::uninitialized();
let mut config: ffi::egl::types::EGLConfig = mem::uninitialized();
if ffi::egl::ChooseConfig(display, attribute_list.as_ptr(), &mut config, 1,
&mut num_config) == 0
{
return Err(OsError(format!("eglChooseConfig failed")))
}
if num_config <= 0 {
return Err(OsError(format!("eglChooseConfig returned no available config")))
}
config
};
android_glue::write_log("eglChooseConfig succeeded");
let context = unsafe {
let mut context_attributes = vec!();
if use_gles2 {
context_attributes.push_all(&[ffi::egl::CONTEXT_CLIENT_VERSION as i32, 2]);
}
context_attributes.push(ffi::egl::NONE as i32);
let context = ffi::egl::CreateContext(display, config, ptr::null(),
context_attributes.as_ptr());
if context.is_null() {
return Err(OsError(format!("eglCreateContext failed")))
}
context
};
android_glue::write_log("eglCreateContext succeeded");
let surface = unsafe {
let surface = ffi::egl::CreateWindowSurface(display, config, native_window, ptr::null());
if surface.is_null() {
return Err(OsError(format!("eglCreateWindowSurface failed")))
}
surface
};
android_glue::write_log("eglCreateWindowSurface succeeded");
let (tx, rx) = channel();
android_glue::add_sender(tx);
Ok(Window {
display: display,
context: context,
surface: surface,
event_rx: rx,
})
}
pub fn is_closed(&self) -> bool {
false
}
pub fn set_title(&self, _: &str) {
}
pub fn show(&self) {
}
pub fn hide(&self) {
}
pub fn get_position(&self) -> Option<(i32, i32)> {
None
}
pub fn set_position(&self, _x: i32, _y: i32) {
}
pub fn get_inner_size(&self) -> Option<(u32, u32)> {
let native_window = unsafe { android_glue::get_native_window() };
if native_window.is_null() {
None
} else {
Some((
unsafe { ffi::ANativeWindow_getWidth(native_window) } as u32,
unsafe { ffi::ANativeWindow_getHeight(native_window) } as u32
))
}
}
pub fn get_outer_size(&self) -> Option<(u32, u32)> {
self.get_inner_size()
}
pub fn set_inner_size(&self, _x: u32, _y: u32) {
}
pub fn create_window_proxy(&self) -> WindowProxy {
WindowProxy
}
pub fn poll_events(&self) -> PollEventsIterator {
PollEventsIterator {
window: self
}
}
pub fn wait_events(&self) -> WaitEventsIterator {
WaitEventsIterator {
window: self
}
}
pub fn make_current(&self) {
unsafe {
ffi::egl::MakeCurrent(self.display, self.surface, self.surface, self.context);
}
}
pub fn is_current(&self) -> bool {
unsafe { ffi::egl::GetCurrentContext() == self.context }
}
pub fn get_proc_address(&self, addr: &str) -> *const () {
let addr = CString::from_slice(addr.as_bytes());
let addr = addr.as_ptr();
unsafe {
ffi::egl::GetProcAddress(addr) as *const ()
}
}
pub fn swap_buffers(&self) {
unsafe {
ffi::egl::SwapBuffers(self.display, self.surface);
}
}
pub fn platform_display(&self) -> *mut libc::c_void {
self.display as *mut libc::c_void
}
pub fn platform_window(&self) -> *mut libc::c_void {
unimplemented!()
}
pub fn get_api(&self) -> ::Api {
::Api::OpenGlEs
}
pub fn set_window_resize_callback(&mut self, _: Option<fn(u32, u32)>) {
}
pub fn set_cursor(&self, _: MouseCursor) {
}
pub fn hidpi_factor(&self) -> f32 {
1.0
}
pub fn set_cursor_position(&self, x: i32, y: i32) -> Result<(), ()> {
unimplemented!();
}
}
unsafe impl Send for Window {}
unsafe impl Sync for Window {}
#[cfg(feature = "window")]
#[derive(Clone)]
pub struct WindowProxy;
impl WindowProxy {
pub fn wakeup_event_loop(&self) {
unimplemented!()
}
}
#[unsafe_destructor]
impl Drop for Window {
fn drop(&mut self) {
use std::ptr;
unsafe {
// we don't call MakeCurrent(0, 0) because we are not sure that the context
// is still the current one
android_glue::write_log("Destroying gl-init window");
ffi::egl::DestroySurface(self.display, self.surface);
ffi::egl::DestroyContext(self.display, self.context);
ffi::egl::Terminate(self.display);
}
}
}
|
PollEventsIterator
|
identifier_name
|
mod.rs
|
extern crate android_glue;
use libc;
use std::ffi::{CString};
use std::sync::mpsc::{Receiver, channel};
use {CreationError, Event, MouseCursor};
use CreationError::OsError;
use events::ElementState::{Pressed, Released};
use events::Event::{MouseInput, MouseMoved};
use events::MouseButton;
use std::collections::VecDeque;
use Api;
use BuilderAttribs;
use GlRequest;
pub struct Window {
display: ffi::egl::types::EGLDisplay,
context: ffi::egl::types::EGLContext,
surface: ffi::egl::types::EGLSurface,
event_rx: Receiver<android_glue::Event>,
}
pub struct MonitorID;
mod ffi;
pub fn get_available_monitors() -> VecDeque <MonitorID> {
let mut rb = VecDeque::new();
rb.push_back(MonitorID);
rb
}
pub fn get_primary_monitor() -> MonitorID {
MonitorID
}
impl MonitorID {
pub fn get_name(&self) -> Option<String> {
Some("Primary".to_string())
}
pub fn get_dimensions(&self) -> (u32, u32) {
unimplemented!()
}
}
#[cfg(feature = "headless")]
pub struct HeadlessContext(i32);
#[cfg(feature = "headless")]
impl HeadlessContext {
/// See the docs in the crate root file.
pub fn new(_builder: BuilderAttribs) -> Result<HeadlessContext, CreationError> {
unimplemented!()
}
/// See the docs in the crate root file.
pub unsafe fn make_current(&self) {
unimplemented!()
}
/// See the docs in the crate root file.
pub fn is_current(&self) -> bool {
unimplemented!()
}
/// See the docs in the crate root file.
pub fn get_proc_address(&self, _addr: &str) -> *const () {
unimplemented!()
}
pub fn get_api(&self) -> ::Api {
::Api::OpenGlEs
}
}
#[cfg(feature = "headless")]
unsafe impl Send for HeadlessContext {}
#[cfg(feature = "headless")]
unsafe impl Sync for HeadlessContext {}
pub struct PollEventsIterator<'a> {
window: &'a Window,
}
impl<'a> Iterator for PollEventsIterator<'a> {
type Item = Event;
fn next(&mut self) -> Option<Event> {
match self.window.event_rx.try_recv() {
Ok(event) => {
match event {
android_glue::Event::EventDown => Some(MouseInput(Pressed, MouseButton::Left)),
android_glue::Event::EventUp => Some(MouseInput(Released, MouseButton::Left)),
android_glue::Event::EventMove(x, y) => Some(MouseMoved((x as i32, y as i32))),
_ => None,
}
}
Err(_) => {
None
}
}
}
}
pub struct WaitEventsIterator<'a> {
window: &'a Window,
}
impl<'a> Iterator for WaitEventsIterator<'a> {
type Item = Event;
fn next(&mut self) -> Option<Event> {
use std::time::Duration;
use std::old_io::timer;
loop {
// calling poll_events()
if let Some(ev) = self.window.poll_events().next() {
return Some(ev);
}
// TODO: Implement a proper way of sleeping on the event queue
timer::sleep(Duration::milliseconds(16));
}
}
}
impl Window {
pub fn new(builder: BuilderAttribs) -> Result<Window, CreationError> {
use std::{mem, ptr};
if builder.sharing.is_some() {
unimplemented!()
}
let native_window = unsafe { android_glue::get_native_window() };
if native_window.is_null() {
return Err(OsError(format!("Android's native window is null")));
}
let display = unsafe {
let display = ffi::egl::GetDisplay(mem::transmute(ffi::egl::DEFAULT_DISPLAY));
if display.is_null() {
return Err(OsError("No EGL display connection available".to_string()));
}
display
};
android_glue::write_log("eglGetDisplay succeeded");
let (_major, _minor) = unsafe {
let mut major: ffi::egl::types::EGLint = mem::uninitialized();
let mut minor: ffi::egl::types::EGLint = mem::uninitialized();
if ffi::egl::Initialize(display, &mut major, &mut minor) == 0 {
return Err(OsError(format!("eglInitialize failed")))
}
(major, minor)
};
android_glue::write_log("eglInitialize succeeded");
let use_gles2 = match builder.gl_version {
GlRequest::Specific(Api::OpenGlEs, (2, _)) => true,
GlRequest::Specific(Api::OpenGlEs, _) => false,
GlRequest::Specific(_, _) => panic!("Only OpenGL ES is supported"), // FIXME: return a result
GlRequest::GlThenGles { opengles_version: (2, _),.. } => true,
_ => false,
};
let mut attribute_list = vec!();
if use_gles2 {
attribute_list.push_all(&[
ffi::egl::RENDERABLE_TYPE as i32,
ffi::egl::OPENGL_ES2_BIT as i32,
]);
}
{
let (red, green, blue) = match builder.color_bits.unwrap_or(24) {
24 => (8, 8, 8),
16 => (6, 5, 6),
_ => panic!("Bad color_bits"),
};
attribute_list.push_all(&[ffi::egl::RED_SIZE as i32, red]);
attribute_list.push_all(&[ffi::egl::GREEN_SIZE as i32, green]);
attribute_list.push_all(&[ffi::egl::BLUE_SIZE as i32, blue]);
}
attribute_list.push_all(&[
ffi::egl::DEPTH_SIZE as i32,
builder.depth_bits.unwrap_or(8) as i32,
]);
attribute_list.push(ffi::egl::NONE as i32);
let config = unsafe {
let mut num_config: ffi::egl::types::EGLint = mem::uninitialized();
let mut config: ffi::egl::types::EGLConfig = mem::uninitialized();
if ffi::egl::ChooseConfig(display, attribute_list.as_ptr(), &mut config, 1,
&mut num_config) == 0
{
return Err(OsError(format!("eglChooseConfig failed")))
}
if num_config <= 0 {
return Err(OsError(format!("eglChooseConfig returned no available config")))
}
config
};
android_glue::write_log("eglChooseConfig succeeded");
let context = unsafe {
let mut context_attributes = vec!();
if use_gles2 {
context_attributes.push_all(&[ffi::egl::CONTEXT_CLIENT_VERSION as i32, 2]);
}
context_attributes.push(ffi::egl::NONE as i32);
let context = ffi::egl::CreateContext(display, config, ptr::null(),
context_attributes.as_ptr());
if context.is_null() {
return Err(OsError(format!("eglCreateContext failed")))
}
context
};
android_glue::write_log("eglCreateContext succeeded");
let surface = unsafe {
let surface = ffi::egl::CreateWindowSurface(display, config, native_window, ptr::null());
if surface.is_null() {
return Err(OsError(format!("eglCreateWindowSurface failed")))
}
surface
};
android_glue::write_log("eglCreateWindowSurface succeeded");
let (tx, rx) = channel();
android_glue::add_sender(tx);
Ok(Window {
display: display,
context: context,
surface: surface,
event_rx: rx,
})
}
pub fn is_closed(&self) -> bool {
false
}
pub fn set_title(&self, _: &str) {
}
pub fn show(&self) {
}
pub fn hide(&self) {
}
pub fn get_position(&self) -> Option<(i32, i32)> {
None
}
pub fn set_position(&self, _x: i32, _y: i32) {
}
pub fn get_inner_size(&self) -> Option<(u32, u32)> {
let native_window = unsafe { android_glue::get_native_window() };
if native_window.is_null() {
None
} else {
Some((
unsafe { ffi::ANativeWindow_getWidth(native_window) } as u32,
unsafe { ffi::ANativeWindow_getHeight(native_window) } as u32
))
}
}
pub fn get_outer_size(&self) -> Option<(u32, u32)> {
self.get_inner_size()
}
pub fn set_inner_size(&self, _x: u32, _y: u32) {
}
pub fn create_window_proxy(&self) -> WindowProxy {
WindowProxy
}
pub fn poll_events(&self) -> PollEventsIterator {
PollEventsIterator {
window: self
}
}
pub fn wait_events(&self) -> WaitEventsIterator {
WaitEventsIterator {
window: self
}
}
pub fn make_current(&self) {
unsafe {
ffi::egl::MakeCurrent(self.display, self.surface, self.surface, self.context);
}
}
pub fn is_current(&self) -> bool {
unsafe { ffi::egl::GetCurrentContext() == self.context }
}
pub fn get_proc_address(&self, addr: &str) -> *const () {
let addr = CString::from_slice(addr.as_bytes());
let addr = addr.as_ptr();
unsafe {
ffi::egl::GetProcAddress(addr) as *const ()
}
}
pub fn swap_buffers(&self) {
unsafe {
ffi::egl::SwapBuffers(self.display, self.surface);
}
}
pub fn platform_display(&self) -> *mut libc::c_void {
self.display as *mut libc::c_void
}
pub fn platform_window(&self) -> *mut libc::c_void {
unimplemented!()
}
pub fn get_api(&self) -> ::Api {
::Api::OpenGlEs
}
pub fn set_window_resize_callback(&mut self, _: Option<fn(u32, u32)>) {
}
pub fn set_cursor(&self, _: MouseCursor) {
}
pub fn hidpi_factor(&self) -> f32 {
1.0
}
pub fn set_cursor_position(&self, x: i32, y: i32) -> Result<(), ()> {
unimplemented!();
}
}
unsafe impl Send for Window {}
unsafe impl Sync for Window {}
|
#[cfg(feature = "window")]
#[derive(Clone)]
pub struct WindowProxy;
impl WindowProxy {
pub fn wakeup_event_loop(&self) {
unimplemented!()
}
}
#[unsafe_destructor]
impl Drop for Window {
fn drop(&mut self) {
use std::ptr;
unsafe {
// we don't call MakeCurrent(0, 0) because we are not sure that the context
// is still the current one
android_glue::write_log("Destroying gl-init window");
ffi::egl::DestroySurface(self.display, self.surface);
ffi::egl::DestroyContext(self.display, self.context);
ffi::egl::Terminate(self.display);
}
}
}
|
random_line_split
|
|
wc.rs
|
/**
* wc (word count) implementation in Rust
*
* The purpose is to learn Rust a bit
*
* author: [email protected]
*
* TODO:
* * word splitting is done on space only, where manual page claims whitespace
* * it is twelve times slower than GNU wc, needs profiling!
*/
use std::io::{BufferedReader, Reader, File, Lines, Buffer, IoError};
use std::os::args;
use std::cmp::max;
#[deriving(Show)]
pub struct WordCount {
pub lines: uint,
pub words: uint,
pub chars: uint,
pub bytes: uint
}
impl WordCount {
fn sum(&mut self, other: &WordCount) {
self.lines += other.lines;
self.words += other.words;
self.chars += other.chars;
self.bytes += other.bytes;
}
}
#[deriving(Show)]
struct Cfg {
pub byte_count: bool,
pub char_count: bool,
pub line_count: bool,
pub word_count: bool,
}
fn is_pwr_ten(i: uint) -> bool {
if i < 10 {
return false;
}
let mut r: uint = i;
while r > 10 {
if r % 10!= 0 {
return false;
}
r = r / 10;
}
return r == 10;
}
fn uint_len(i: uint) -> uint {
if i < 10 {
return 1;
}
let ret = (i as f64).log10().ceil() as uint;
if is_pwr_ten(i) {
return ret +1;
}
ret
}
#[test]
fn test_int_len() {
for i in range(0u, 10002) {
let s = format!("{:u}", i);
//assert_eq!(s.len(), int_len(i));
println!("{:u} {}", i, uint_len(i));
}
}
#[test]
fn test_is_pwr_ten() {
for i in range(0u, 1002) {
if i == 10 || i == 100 || i == 1000
|
else {
assert_eq!(is_pwr_ten(i), false);
}
}
}
fn wc<'r, T: Buffer>(lines : &'r mut Lines<'r, T>) -> Result<WordCount, IoError> {
let mut ret : WordCount = WordCount { lines: 0u, words: 0u, chars: 0u, bytes: 0u };
for res in lines {
let line = try!(res);
let slice: &str = line.as_slice();
ret.lines += 1;
ret.words += slice.split(' ').count();
ret.chars += slice.chars().count();
ret.bytes += slice.bytes().count();
}
return Ok(ret);
}
fn parse_args(args: Vec<String>) -> (Cfg, Vec<String>) {
let mut cfg = Cfg{byte_count: false, char_count: false, line_count: false, word_count: false};
let mut idx = 1u;
let mut paths = Vec::new();
while idx < args.len() {
match args[idx].as_slice() {
"--lines" => cfg.line_count = true,
"-l" => cfg.line_count = true,
"--bytes" => cfg.byte_count = true,
"-c" => cfg.byte_count = true,
"--chars" => cfg.char_count = true,
"-m" => cfg.char_count = true,
"--words" => cfg.word_count = true,
"-w" => cfg.word_count = true,
_ => paths.push(args[idx].clone()) //FIXME: unecessary clone
}
idx += 1;
}
if!cfg.byte_count && (!cfg.char_count &&! cfg.line_count &&!cfg.word_count) {
cfg.char_count = true;
cfg.line_count = true;
cfg.word_count = true;
}
(cfg, paths)
}
fn spaces(n: uint) -> String {
let mut ret = String::with_capacity(n);
for _ in range(0, n) {
ret.push(' ');
}
ret
}
fn uipad(i: uint, maxlen: uint) -> String {
let strlen = uint_len(i);
if strlen >= maxlen {
return format!("{:u}", i);
}
return format!("{:s}{:u}", spaces(maxlen - strlen), i);
}
//newline, word, character, byte, maximum line length
fn print_results(results : &Vec<(WordCount, &str)>, cfg: &Cfg) {
let mut lines_maxlen = 0u;
let mut words_maxlen = 0u;
let mut chars_maxlen = 0u;
let mut bytes_maxlen = 0u;
for &(wc, _) in results.iter() {
lines_maxlen = max(lines_maxlen, wc.lines);
words_maxlen = max(words_maxlen, wc.words);
chars_maxlen = max(chars_maxlen, wc.chars);
bytes_maxlen = max(bytes_maxlen, wc.bytes);
}
lines_maxlen = uint_len(lines_maxlen);
words_maxlen = uint_len(words_maxlen);
chars_maxlen = uint_len(chars_maxlen);
bytes_maxlen = uint_len(bytes_maxlen);
for i in results.iter() {
let (wc, path) = *i;
let mut fmtbuf = String::from_str("");
if cfg.line_count {
fmtbuf = format!("{:s} {:s}", fmtbuf, uipad(wc.lines, lines_maxlen));
}
//TODO: format! creates new object, investigate things like extend
if cfg.word_count {
fmtbuf = format!("{:s} {:s}", fmtbuf, uipad(wc.words, words_maxlen));
}
if cfg.char_count {
fmtbuf = format!("{:s} {:s}", fmtbuf, uipad(wc.chars, chars_maxlen));
}
if cfg.byte_count {
fmtbuf = format!("{:s} {:s}", fmtbuf, uipad(wc.bytes, bytes_maxlen));
}
println!("{:s} {:s}", fmtbuf, path);
}
}
fn main() {
let (cfg, paths) = parse_args(args());
println!("cfg: {}, paths: {}", cfg, paths);
if paths.len() == 0 {
fail!("Reading from stdin is not yet implemented");
}
let mut total : WordCount = WordCount { lines: 0u, words: 0u, chars: 0u, bytes: 0u };
let mut results = Vec::with_capacity(paths.len());
for path_i in paths.iter() {
let path = path_i.as_slice();
// TODO: clone is just a workaround
let p = Path::new(path);
// errors can be checked on opening file...
let f = match File::open(&p) {
Err(why) => fail!("Can't open {}: {}", p.display(), why.desc),
Ok(f) => f,
};
let mut br = BufferedReader::new(f);
let res = match wc(&mut br.lines()) {
Ok(res) => res,
Err(e) => fail!(e)
};
total.sum(&res);
results.push((res, path));
}
if paths.len() > 1 {
results.push((total, "total"));
}
print_results(&results, &cfg);
}
|
{
assert_eq!(is_pwr_ten(i), true);
}
|
conditional_block
|
wc.rs
|
/**
* wc (word count) implementation in Rust
*
* The purpose is to learn Rust a bit
*
* author: [email protected]
*
* TODO:
* * word splitting is done on space only, where manual page claims whitespace
* * it is twelve times slower than GNU wc, needs profiling!
*/
use std::io::{BufferedReader, Reader, File, Lines, Buffer, IoError};
use std::os::args;
use std::cmp::max;
#[deriving(Show)]
pub struct WordCount {
pub lines: uint,
pub words: uint,
pub chars: uint,
pub bytes: uint
}
impl WordCount {
fn sum(&mut self, other: &WordCount) {
self.lines += other.lines;
self.words += other.words;
self.chars += other.chars;
self.bytes += other.bytes;
}
}
#[deriving(Show)]
struct Cfg {
pub byte_count: bool,
pub char_count: bool,
pub line_count: bool,
pub word_count: bool,
}
fn is_pwr_ten(i: uint) -> bool {
if i < 10 {
return false;
}
let mut r: uint = i;
while r > 10 {
if r % 10!= 0 {
return false;
}
r = r / 10;
}
return r == 10;
}
fn uint_len(i: uint) -> uint {
if i < 10 {
return 1;
}
let ret = (i as f64).log10().ceil() as uint;
if is_pwr_ten(i) {
return ret +1;
}
ret
}
#[test]
fn test_int_len() {
for i in range(0u, 10002) {
let s = format!("{:u}", i);
//assert_eq!(s.len(), int_len(i));
println!("{:u} {}", i, uint_len(i));
}
}
#[test]
fn test_is_pwr_ten() {
for i in range(0u, 1002) {
if i == 10 || i == 100 || i == 1000 {
assert_eq!(is_pwr_ten(i), true);
}
else {
assert_eq!(is_pwr_ten(i), false);
}
}
}
fn
|
<'r, T: Buffer>(lines : &'r mut Lines<'r, T>) -> Result<WordCount, IoError> {
let mut ret : WordCount = WordCount { lines: 0u, words: 0u, chars: 0u, bytes: 0u };
for res in lines {
let line = try!(res);
let slice: &str = line.as_slice();
ret.lines += 1;
ret.words += slice.split(' ').count();
ret.chars += slice.chars().count();
ret.bytes += slice.bytes().count();
}
return Ok(ret);
}
fn parse_args(args: Vec<String>) -> (Cfg, Vec<String>) {
let mut cfg = Cfg{byte_count: false, char_count: false, line_count: false, word_count: false};
let mut idx = 1u;
let mut paths = Vec::new();
while idx < args.len() {
match args[idx].as_slice() {
"--lines" => cfg.line_count = true,
"-l" => cfg.line_count = true,
"--bytes" => cfg.byte_count = true,
"-c" => cfg.byte_count = true,
"--chars" => cfg.char_count = true,
"-m" => cfg.char_count = true,
"--words" => cfg.word_count = true,
"-w" => cfg.word_count = true,
_ => paths.push(args[idx].clone()) //FIXME: unecessary clone
}
idx += 1;
}
if!cfg.byte_count && (!cfg.char_count &&! cfg.line_count &&!cfg.word_count) {
cfg.char_count = true;
cfg.line_count = true;
cfg.word_count = true;
}
(cfg, paths)
}
fn spaces(n: uint) -> String {
let mut ret = String::with_capacity(n);
for _ in range(0, n) {
ret.push(' ');
}
ret
}
fn uipad(i: uint, maxlen: uint) -> String {
let strlen = uint_len(i);
if strlen >= maxlen {
return format!("{:u}", i);
}
return format!("{:s}{:u}", spaces(maxlen - strlen), i);
}
//newline, word, character, byte, maximum line length
fn print_results(results : &Vec<(WordCount, &str)>, cfg: &Cfg) {
let mut lines_maxlen = 0u;
let mut words_maxlen = 0u;
let mut chars_maxlen = 0u;
let mut bytes_maxlen = 0u;
for &(wc, _) in results.iter() {
lines_maxlen = max(lines_maxlen, wc.lines);
words_maxlen = max(words_maxlen, wc.words);
chars_maxlen = max(chars_maxlen, wc.chars);
bytes_maxlen = max(bytes_maxlen, wc.bytes);
}
lines_maxlen = uint_len(lines_maxlen);
words_maxlen = uint_len(words_maxlen);
chars_maxlen = uint_len(chars_maxlen);
bytes_maxlen = uint_len(bytes_maxlen);
for i in results.iter() {
let (wc, path) = *i;
let mut fmtbuf = String::from_str("");
if cfg.line_count {
fmtbuf = format!("{:s} {:s}", fmtbuf, uipad(wc.lines, lines_maxlen));
}
//TODO: format! creates new object, investigate things like extend
if cfg.word_count {
fmtbuf = format!("{:s} {:s}", fmtbuf, uipad(wc.words, words_maxlen));
}
if cfg.char_count {
fmtbuf = format!("{:s} {:s}", fmtbuf, uipad(wc.chars, chars_maxlen));
}
if cfg.byte_count {
fmtbuf = format!("{:s} {:s}", fmtbuf, uipad(wc.bytes, bytes_maxlen));
}
println!("{:s} {:s}", fmtbuf, path);
}
}
fn main() {
let (cfg, paths) = parse_args(args());
println!("cfg: {}, paths: {}", cfg, paths);
if paths.len() == 0 {
fail!("Reading from stdin is not yet implemented");
}
let mut total : WordCount = WordCount { lines: 0u, words: 0u, chars: 0u, bytes: 0u };
let mut results = Vec::with_capacity(paths.len());
for path_i in paths.iter() {
let path = path_i.as_slice();
// TODO: clone is just a workaround
let p = Path::new(path);
// errors can be checked on opening file...
let f = match File::open(&p) {
Err(why) => fail!("Can't open {}: {}", p.display(), why.desc),
Ok(f) => f,
};
let mut br = BufferedReader::new(f);
let res = match wc(&mut br.lines()) {
Ok(res) => res,
Err(e) => fail!(e)
};
total.sum(&res);
results.push((res, path));
}
if paths.len() > 1 {
results.push((total, "total"));
}
print_results(&results, &cfg);
}
|
wc
|
identifier_name
|
wc.rs
|
/**
* wc (word count) implementation in Rust
*
* The purpose is to learn Rust a bit
*
* author: [email protected]
*
* TODO:
* * word splitting is done on space only, where manual page claims whitespace
* * it is twelve times slower than GNU wc, needs profiling!
*/
use std::io::{BufferedReader, Reader, File, Lines, Buffer, IoError};
use std::os::args;
use std::cmp::max;
#[deriving(Show)]
pub struct WordCount {
pub lines: uint,
pub words: uint,
pub chars: uint,
pub bytes: uint
}
impl WordCount {
fn sum(&mut self, other: &WordCount) {
self.lines += other.lines;
self.words += other.words;
self.chars += other.chars;
self.bytes += other.bytes;
}
}
#[deriving(Show)]
struct Cfg {
pub byte_count: bool,
pub char_count: bool,
pub line_count: bool,
pub word_count: bool,
}
fn is_pwr_ten(i: uint) -> bool {
if i < 10 {
return false;
}
let mut r: uint = i;
while r > 10 {
if r % 10!= 0 {
return false;
}
r = r / 10;
}
return r == 10;
}
fn uint_len(i: uint) -> uint {
if i < 10 {
return 1;
}
let ret = (i as f64).log10().ceil() as uint;
if is_pwr_ten(i) {
return ret +1;
}
ret
}
#[test]
fn test_int_len() {
for i in range(0u, 10002) {
let s = format!("{:u}", i);
//assert_eq!(s.len(), int_len(i));
println!("{:u} {}", i, uint_len(i));
}
}
#[test]
fn test_is_pwr_ten() {
for i in range(0u, 1002) {
if i == 10 || i == 100 || i == 1000 {
assert_eq!(is_pwr_ten(i), true);
}
else {
assert_eq!(is_pwr_ten(i), false);
}
}
}
fn wc<'r, T: Buffer>(lines : &'r mut Lines<'r, T>) -> Result<WordCount, IoError> {
let mut ret : WordCount = WordCount { lines: 0u, words: 0u, chars: 0u, bytes: 0u };
for res in lines {
let line = try!(res);
let slice: &str = line.as_slice();
ret.lines += 1;
ret.words += slice.split(' ').count();
ret.chars += slice.chars().count();
ret.bytes += slice.bytes().count();
}
return Ok(ret);
}
|
while idx < args.len() {
match args[idx].as_slice() {
"--lines" => cfg.line_count = true,
"-l" => cfg.line_count = true,
"--bytes" => cfg.byte_count = true,
"-c" => cfg.byte_count = true,
"--chars" => cfg.char_count = true,
"-m" => cfg.char_count = true,
"--words" => cfg.word_count = true,
"-w" => cfg.word_count = true,
_ => paths.push(args[idx].clone()) //FIXME: unecessary clone
}
idx += 1;
}
if!cfg.byte_count && (!cfg.char_count &&! cfg.line_count &&!cfg.word_count) {
cfg.char_count = true;
cfg.line_count = true;
cfg.word_count = true;
}
(cfg, paths)
}
fn spaces(n: uint) -> String {
let mut ret = String::with_capacity(n);
for _ in range(0, n) {
ret.push(' ');
}
ret
}
fn uipad(i: uint, maxlen: uint) -> String {
let strlen = uint_len(i);
if strlen >= maxlen {
return format!("{:u}", i);
}
return format!("{:s}{:u}", spaces(maxlen - strlen), i);
}
//newline, word, character, byte, maximum line length
fn print_results(results : &Vec<(WordCount, &str)>, cfg: &Cfg) {
let mut lines_maxlen = 0u;
let mut words_maxlen = 0u;
let mut chars_maxlen = 0u;
let mut bytes_maxlen = 0u;
for &(wc, _) in results.iter() {
lines_maxlen = max(lines_maxlen, wc.lines);
words_maxlen = max(words_maxlen, wc.words);
chars_maxlen = max(chars_maxlen, wc.chars);
bytes_maxlen = max(bytes_maxlen, wc.bytes);
}
lines_maxlen = uint_len(lines_maxlen);
words_maxlen = uint_len(words_maxlen);
chars_maxlen = uint_len(chars_maxlen);
bytes_maxlen = uint_len(bytes_maxlen);
for i in results.iter() {
let (wc, path) = *i;
let mut fmtbuf = String::from_str("");
if cfg.line_count {
fmtbuf = format!("{:s} {:s}", fmtbuf, uipad(wc.lines, lines_maxlen));
}
//TODO: format! creates new object, investigate things like extend
if cfg.word_count {
fmtbuf = format!("{:s} {:s}", fmtbuf, uipad(wc.words, words_maxlen));
}
if cfg.char_count {
fmtbuf = format!("{:s} {:s}", fmtbuf, uipad(wc.chars, chars_maxlen));
}
if cfg.byte_count {
fmtbuf = format!("{:s} {:s}", fmtbuf, uipad(wc.bytes, bytes_maxlen));
}
println!("{:s} {:s}", fmtbuf, path);
}
}
fn main() {
let (cfg, paths) = parse_args(args());
println!("cfg: {}, paths: {}", cfg, paths);
if paths.len() == 0 {
fail!("Reading from stdin is not yet implemented");
}
let mut total : WordCount = WordCount { lines: 0u, words: 0u, chars: 0u, bytes: 0u };
let mut results = Vec::with_capacity(paths.len());
for path_i in paths.iter() {
let path = path_i.as_slice();
// TODO: clone is just a workaround
let p = Path::new(path);
// errors can be checked on opening file...
let f = match File::open(&p) {
Err(why) => fail!("Can't open {}: {}", p.display(), why.desc),
Ok(f) => f,
};
let mut br = BufferedReader::new(f);
let res = match wc(&mut br.lines()) {
Ok(res) => res,
Err(e) => fail!(e)
};
total.sum(&res);
results.push((res, path));
}
if paths.len() > 1 {
results.push((total, "total"));
}
print_results(&results, &cfg);
}
|
fn parse_args(args: Vec<String>) -> (Cfg, Vec<String>) {
let mut cfg = Cfg{byte_count: false, char_count: false, line_count: false, word_count: false};
let mut idx = 1u;
let mut paths = Vec::new();
|
random_line_split
|
wc.rs
|
/**
* wc (word count) implementation in Rust
*
* The purpose is to learn Rust a bit
*
* author: [email protected]
*
* TODO:
* * word splitting is done on space only, where manual page claims whitespace
* * it is twelve times slower than GNU wc, needs profiling!
*/
use std::io::{BufferedReader, Reader, File, Lines, Buffer, IoError};
use std::os::args;
use std::cmp::max;
#[deriving(Show)]
pub struct WordCount {
pub lines: uint,
pub words: uint,
pub chars: uint,
pub bytes: uint
}
impl WordCount {
fn sum(&mut self, other: &WordCount) {
self.lines += other.lines;
self.words += other.words;
self.chars += other.chars;
self.bytes += other.bytes;
}
}
#[deriving(Show)]
struct Cfg {
pub byte_count: bool,
pub char_count: bool,
pub line_count: bool,
pub word_count: bool,
}
fn is_pwr_ten(i: uint) -> bool {
if i < 10 {
return false;
}
let mut r: uint = i;
while r > 10 {
if r % 10!= 0 {
return false;
}
r = r / 10;
}
return r == 10;
}
fn uint_len(i: uint) -> uint {
if i < 10 {
return 1;
}
let ret = (i as f64).log10().ceil() as uint;
if is_pwr_ten(i) {
return ret +1;
}
ret
}
#[test]
fn test_int_len() {
for i in range(0u, 10002) {
let s = format!("{:u}", i);
//assert_eq!(s.len(), int_len(i));
println!("{:u} {}", i, uint_len(i));
}
}
#[test]
fn test_is_pwr_ten() {
for i in range(0u, 1002) {
if i == 10 || i == 100 || i == 1000 {
assert_eq!(is_pwr_ten(i), true);
}
else {
assert_eq!(is_pwr_ten(i), false);
}
}
}
fn wc<'r, T: Buffer>(lines : &'r mut Lines<'r, T>) -> Result<WordCount, IoError> {
let mut ret : WordCount = WordCount { lines: 0u, words: 0u, chars: 0u, bytes: 0u };
for res in lines {
let line = try!(res);
let slice: &str = line.as_slice();
ret.lines += 1;
ret.words += slice.split(' ').count();
ret.chars += slice.chars().count();
ret.bytes += slice.bytes().count();
}
return Ok(ret);
}
fn parse_args(args: Vec<String>) -> (Cfg, Vec<String>)
|
if!cfg.byte_count && (!cfg.char_count &&! cfg.line_count &&!cfg.word_count) {
cfg.char_count = true;
cfg.line_count = true;
cfg.word_count = true;
}
(cfg, paths)
}
fn spaces(n: uint) -> String {
let mut ret = String::with_capacity(n);
for _ in range(0, n) {
ret.push(' ');
}
ret
}
fn uipad(i: uint, maxlen: uint) -> String {
let strlen = uint_len(i);
if strlen >= maxlen {
return format!("{:u}", i);
}
return format!("{:s}{:u}", spaces(maxlen - strlen), i);
}
//newline, word, character, byte, maximum line length
fn print_results(results : &Vec<(WordCount, &str)>, cfg: &Cfg) {
let mut lines_maxlen = 0u;
let mut words_maxlen = 0u;
let mut chars_maxlen = 0u;
let mut bytes_maxlen = 0u;
for &(wc, _) in results.iter() {
lines_maxlen = max(lines_maxlen, wc.lines);
words_maxlen = max(words_maxlen, wc.words);
chars_maxlen = max(chars_maxlen, wc.chars);
bytes_maxlen = max(bytes_maxlen, wc.bytes);
}
lines_maxlen = uint_len(lines_maxlen);
words_maxlen = uint_len(words_maxlen);
chars_maxlen = uint_len(chars_maxlen);
bytes_maxlen = uint_len(bytes_maxlen);
for i in results.iter() {
let (wc, path) = *i;
let mut fmtbuf = String::from_str("");
if cfg.line_count {
fmtbuf = format!("{:s} {:s}", fmtbuf, uipad(wc.lines, lines_maxlen));
}
//TODO: format! creates new object, investigate things like extend
if cfg.word_count {
fmtbuf = format!("{:s} {:s}", fmtbuf, uipad(wc.words, words_maxlen));
}
if cfg.char_count {
fmtbuf = format!("{:s} {:s}", fmtbuf, uipad(wc.chars, chars_maxlen));
}
if cfg.byte_count {
fmtbuf = format!("{:s} {:s}", fmtbuf, uipad(wc.bytes, bytes_maxlen));
}
println!("{:s} {:s}", fmtbuf, path);
}
}
fn main() {
let (cfg, paths) = parse_args(args());
println!("cfg: {}, paths: {}", cfg, paths);
if paths.len() == 0 {
fail!("Reading from stdin is not yet implemented");
}
let mut total : WordCount = WordCount { lines: 0u, words: 0u, chars: 0u, bytes: 0u };
let mut results = Vec::with_capacity(paths.len());
for path_i in paths.iter() {
let path = path_i.as_slice();
// TODO: clone is just a workaround
let p = Path::new(path);
// errors can be checked on opening file...
let f = match File::open(&p) {
Err(why) => fail!("Can't open {}: {}", p.display(), why.desc),
Ok(f) => f,
};
let mut br = BufferedReader::new(f);
let res = match wc(&mut br.lines()) {
Ok(res) => res,
Err(e) => fail!(e)
};
total.sum(&res);
results.push((res, path));
}
if paths.len() > 1 {
results.push((total, "total"));
}
print_results(&results, &cfg);
}
|
{
let mut cfg = Cfg{byte_count: false, char_count: false, line_count: false, word_count: false};
let mut idx = 1u;
let mut paths = Vec::new();
while idx < args.len() {
match args[idx].as_slice() {
"--lines" => cfg.line_count = true,
"-l" => cfg.line_count = true,
"--bytes" => cfg.byte_count = true,
"-c" => cfg.byte_count = true,
"--chars" => cfg.char_count = true,
"-m" => cfg.char_count = true,
"--words" => cfg.word_count = true,
"-w" => cfg.word_count = true,
_ => paths.push(args[idx].clone()) //FIXME: unecessary clone
}
idx += 1;
}
|
identifier_body
|
net.rs
|
use color::Colorf32;
use fastup::{self, Node, parse_for_first_node, parse_color};
use stats_once::{NET_DOWNLOAD_SPEED, NET_UPLOAD_SPEED};
use super::error_node;
use std::mem::swap;
#[derive(Debug, Copy, Clone, Default)]
pub struct Widget;
impl super::Widget for Widget {
fn expand(&self, args: Vec<String>) -> Node {
match args.len() {
4 | 6 => node_from_args(args),
8 => node_from_args(args), // debug only
_ => error_node("(ccdd44: net) takes 4 or 6 arguments \\(speed in KiB\\): color-cold\\|color-hot\\|lo-speed\\|hi-speed{\\|lo-speed-upload\\|hi-speed-upload}"),
}
}
}
fn node_from_args(args: Vec<String>) -> Node {
try_node_from_args(args).unwrap_or_else(|e| error_node(&e))
}
fn try_node_from_args(args: Vec<String>) -> Result<Node, String> {
assert!((args.len() == 4 || args.len() == 6) || args.len() == 8);
let cold = parse_color(&args[0]).map_err(escape_fastup)?;
let hot = parse_color(&args[1]).map_err(escape_fastup)?;
let parse_speed = |i| -> Result<Option<u64>, String> {
if args.len() <= i || args[i].trim().len() == 0 {
Ok(None)
} else {
let speed: f64 = args[i].parse().map_err(escape_fastup)?;
if speed < 0.0 {
Err(format!("speed cannot be a negative number, but got {}", speed))
} else {
Ok(Some((speed * 1024.0) as u64))
}
}
};
let lo_speed_down = parse_speed(2)?.unwrap();
let hi_speed_down = parse_speed(3)?.unwrap();
let lo_speed_up = parse_speed(4)?.unwrap_or(lo_speed_down);
let hi_speed_up = parse_speed(5)?.unwrap_or(hi_speed_down);
let speed_down = parse_speed(6)?.unwrap_or(*NET_DOWNLOAD_SPEED);
let speed_up = parse_speed(7)?.unwrap_or(*NET_UPLOAD_SPEED);
Ok(
net_node(
cold.into(),
hot.into(),
lo_speed_down,
hi_speed_down,
lo_speed_up,
hi_speed_up,
speed_down,
speed_up,
)
)
|
fn net_node(
cold: Colorf32,
hot: Colorf32,
lo_speed_down: u64,
hi_speed_down: u64,
lo_speed_up: u64,
hi_speed_up: u64,
speed_down: u64,
speed_up: u64,
) -> Node
{
const BG_LIGHTNESS: f32 = 0.15;
const FG_LIGHTNESS: f32 = 0.4;
const IDLE_LIGHTNESS: f32 = 0.2;
const FAST_LIGHTNESS_BOOST: f32 = 0.3;
const PROGRESS_INDICATORS: &'static str = "▁▂▃▄▅▆▇";
let ratio_of = |x, lo, hi| nan_to_zero(unmix(x as f32, (lo as f32, hi as f32)));
let ratio_down = ratio_of(speed_down, lo_speed_down, hi_speed_down);
let ratio_up = ratio_of(speed_up, lo_speed_up, hi_speed_up);
let (fast_speed, fast_ratio, fast_boost, boost_down, boost_up) = {
if speed_down == 0 && speed_up == 0 {
(0, 0.0, 0.0, 0.0, 0.0)
} else if (ratio_up - ratio_down).abs() < 1e-5 {
(speed_down, ratio_down, FAST_LIGHTNESS_BOOST, FAST_LIGHTNESS_BOOST, 0.0)
} else if ratio_up > ratio_down {
(speed_up, ratio_up, FAST_LIGHTNESS_BOOST, 0.0, FAST_LIGHTNESS_BOOST)
} else {
(speed_down, ratio_down, FAST_LIGHTNESS_BOOST, FAST_LIGHTNESS_BOOST, 0.0)
}
};
let fast_ratio = fast_ratio.max(0.0).min(1.0);
let ratio_down = ratio_down.max(0.0).min(1.0);
let ratio_up = ratio_up .max(0.0).min(1.0);
let bg_cold = cold.set_lightness(BG_LIGHTNESS);
let bg_hot = hot.set_lightness(BG_LIGHTNESS);
let bg = bg_cold.mix(bg_hot, fast_ratio).clamp_to_888();
let idle_for = |ratio: f32, boost: f32| {
let idle_cold = cold.set_lightness(IDLE_LIGHTNESS + boost);
let idle_hot = hot.set_lightness(IDLE_LIGHTNESS + boost);
idle_cold.mix(idle_hot, ratio).clamp_to_888()
};
let fg_for = |ratio: f32, boost: f32| {
if ratio == 0.0 {
idle_for(ratio, boost)
} else {
let fg_cold = cold.set_lightness(FG_LIGHTNESS + boost);
let fg_hot = hot.set_lightness(FG_LIGHTNESS + boost);
fg_cold.mix(fg_hot, ratio).clamp_to_888()
}
};
let indicator_for = |ratio: f32, reverse: bool| {
let len = PROGRESS_INDICATORS.chars().count() as f32;
let mut i = (len * ratio).floor();
if reverse { i = len - 1.0 - i }
let i = i.min(len - 1.0).max(0.0) as usize;
PROGRESS_INDICATORS.chars().nth(i).unwrap()
};
let styled_indicator_for = |ratio: f32, boost: f32, upside_down: bool| {
let mut fg = fg_for(ratio, boost);
let mut bg = bg;
if upside_down { swap(&mut fg, &mut bg) }
let indicator = indicator_for(ratio, upside_down);
format!("[{}:({}:{})]", bg, fg, indicator)
};
let indicator_down = styled_indicator_for(ratio_down, boost_down, true);
let indicator_up = styled_indicator_for(ratio_up, boost_up, false);
let fast_text = {
let fg_fast = fg_for(fast_ratio, fast_boost);
let text = format_byte_size(fast_speed);
let text = format!("{:>5}", text);
let text = escape_fastup(text);
format!("({}:{})", fg_fast, text)
};
let node = format!("[{}: \\ {}{}{} ]", bg, indicator_up, indicator_down, fast_text);
parse_for_first_node(&node).unwrap()
}
fn escape_fastup<T>(input: T) -> String
where T: ToString
{
fastup::escape_for_text(&input.to_string())
}
/// Format byte size into short and human readable form.
///
/// Shortness is the most important considering factor here.
/// The largest unit is 'G'.
//
// 0B
// 10B
// 100B
// 999B
// 0.9K
// 9.0K
// 10K
// 100K
//...
//
// NOTE: There are NO spaces in front of the result.
fn format_byte_size(size: u64) -> String {
let (size, unit) = find_byte_size_unit(size);
if unit == 'B' {
format!("{}{}", size.floor(), unit)
} else {
if size < 10.0 {
format!("{:.1}{}", (size * 10.0).floor() / 10.0, unit)
} else {
format!("{}{}", size.floor(), unit)
}
}
}
fn find_byte_size_unit(size: u64) -> (f64, char) {
const UNITS: &'static str = "BKM";
let mut size = size as f64;
for unit in UNITS.chars() {
if size > 999.9 {
size /= 1024.0;
} else {
return (size, unit);
}
}
(size, 'G')
}
fn unmix(x: f32, range: (f32, f32)) -> f32 {
let (a, b) = range;
(x - a) / (b - a)
}
fn nan_to_zero(x: f32) -> f32 {
if x.is_nan() { 0.0 } else { x }
}
|
}
|
random_line_split
|
net.rs
|
use color::Colorf32;
use fastup::{self, Node, parse_for_first_node, parse_color};
use stats_once::{NET_DOWNLOAD_SPEED, NET_UPLOAD_SPEED};
use super::error_node;
use std::mem::swap;
#[derive(Debug, Copy, Clone, Default)]
pub struct Widget;
impl super::Widget for Widget {
fn expand(&self, args: Vec<String>) -> Node {
match args.len() {
4 | 6 => node_from_args(args),
8 => node_from_args(args), // debug only
_ => error_node("(ccdd44: net) takes 4 or 6 arguments \\(speed in KiB\\): color-cold\\|color-hot\\|lo-speed\\|hi-speed{\\|lo-speed-upload\\|hi-speed-upload}"),
}
}
}
fn node_from_args(args: Vec<String>) -> Node {
try_node_from_args(args).unwrap_or_else(|e| error_node(&e))
}
fn try_node_from_args(args: Vec<String>) -> Result<Node, String> {
assert!((args.len() == 4 || args.len() == 6) || args.len() == 8);
let cold = parse_color(&args[0]).map_err(escape_fastup)?;
let hot = parse_color(&args[1]).map_err(escape_fastup)?;
let parse_speed = |i| -> Result<Option<u64>, String> {
if args.len() <= i || args[i].trim().len() == 0 {
Ok(None)
} else {
let speed: f64 = args[i].parse().map_err(escape_fastup)?;
if speed < 0.0 {
Err(format!("speed cannot be a negative number, but got {}", speed))
} else {
Ok(Some((speed * 1024.0) as u64))
}
}
};
let lo_speed_down = parse_speed(2)?.unwrap();
let hi_speed_down = parse_speed(3)?.unwrap();
let lo_speed_up = parse_speed(4)?.unwrap_or(lo_speed_down);
let hi_speed_up = parse_speed(5)?.unwrap_or(hi_speed_down);
let speed_down = parse_speed(6)?.unwrap_or(*NET_DOWNLOAD_SPEED);
let speed_up = parse_speed(7)?.unwrap_or(*NET_UPLOAD_SPEED);
Ok(
net_node(
cold.into(),
hot.into(),
lo_speed_down,
hi_speed_down,
lo_speed_up,
hi_speed_up,
speed_down,
speed_up,
)
)
}
fn net_node(
cold: Colorf32,
hot: Colorf32,
lo_speed_down: u64,
hi_speed_down: u64,
lo_speed_up: u64,
hi_speed_up: u64,
speed_down: u64,
speed_up: u64,
) -> Node
{
const BG_LIGHTNESS: f32 = 0.15;
const FG_LIGHTNESS: f32 = 0.4;
const IDLE_LIGHTNESS: f32 = 0.2;
const FAST_LIGHTNESS_BOOST: f32 = 0.3;
const PROGRESS_INDICATORS: &'static str = "▁▂▃▄▅▆▇";
let ratio_of = |x, lo, hi| nan_to_zero(unmix(x as f32, (lo as f32, hi as f32)));
let ratio_down = ratio_of(speed_down, lo_speed_down, hi_speed_down);
let ratio_up = ratio_of(speed_up, lo_speed_up, hi_speed_up);
let (fast_speed, fast_ratio, fast_boost, boost_down, boost_up) = {
if speed_down == 0 && speed_up == 0 {
(0, 0.0, 0.0, 0.0, 0.0)
} else if (ratio_up - ratio_down).abs() < 1e-5 {
(speed_down, ratio_down, FAST_LIGHTNESS_BOOST, FAST_LIGHTNESS_BOOST, 0.0)
} else if ratio_up > ratio_down {
(speed_up, ratio_up, FAST_LIGHTNESS_BOOST, 0.0, FAST_LIGHTNESS_BOOST)
} else {
(speed_down, ratio_down, FAST_LIGHTNESS_BOOST, FAST_LIGHTNESS_BOOST, 0.0)
}
};
let fast_ratio = fast_ratio.max(0.0).min(1.0);
let ratio_down = ratio_down.max(0.0).min(1.0);
let ratio_up = ratio_up .max(0.0).min(1.0);
let bg_cold = cold.set_lightness(BG_LIGHTNESS);
let bg_hot = hot.set_lightness(BG_LIGHTNESS);
let bg = bg_cold.mix(bg_hot, fast_ratio).clamp_to_888();
let idle_for = |ratio: f32, boost: f32| {
let idle_cold = cold.set_lightness(IDLE_LIGHTNESS + boost);
let idle_hot = hot.set_lightness(IDLE_LIGHTNESS + boost);
idle_cold.mix(idle_hot, ratio).clamp_to_888()
};
let fg_for = |ratio: f32, boost: f32| {
if ratio == 0.0 {
idle_for(ratio, boost)
} else {
let fg_cold = cold.set_lightness(FG_LIGHTNESS + boost);
let fg_hot = hot.set_lightness(FG_LIGHTNESS + boost);
fg_cold.mix(fg_hot, ratio).clamp_to_888()
}
};
let indicator_for = |ratio: f32, reverse: bool| {
let len = PROGRESS_INDICATORS.chars().count() as f32;
let mut i = (len * ratio).floor();
if reverse { i = len - 1.0 - i }
let i = i.min(len - 1.0).max(0.0) as usize;
PROGRESS_INDICATORS.chars().nth(i).unwrap()
};
let styled_indicator_for = |ratio: f32, boost: f32, upside_down: bool| {
let mut fg = fg_for(ratio, boost);
let mut bg = bg;
if upside_down { swap(&mut fg, &mut bg) }
let indicator = indicator_for(ratio, upside_down);
format!("[{}:({}:{})]", bg, fg, indicator)
};
let indicator_down = styled_indicator_for(ratio_down, boost_down, true);
let indicator_up = styled_indicator_for(ratio_up, boost_up, false);
let fast_text = {
let fg_fast = fg_for(fast_ratio, fast_boost);
let text = format_byte_size(fast_speed);
let text = format!("{:>5}", text);
let text = escape_fastup(text);
format!("({}:{})", fg_fast, text)
};
let node = format!("[{}: \\ {}{}{} ]", bg, indicator_up, indicator_down, fast_text);
parse_for_first_node(&node).unwrap()
}
fn escape_fastup<T>(input: T) -> String
where T: ToString
{
fastup::escape_for_text(&input.to_string())
}
/// Format byte size into short and human readable form.
///
/// Shortness is the most important considering factor here.
/// The largest unit is 'G'.
//
// 0B
// 10B
// 100B
// 999B
// 0.9K
// 9.0K
// 10K
// 100K
//...
//
// NOTE: There are NO spaces in front of the result.
fn format_byte_size(size: u64) -> String {
let (size, unit) = find_byte_size_unit(size);
if unit == 'B' {
format!("{}{}", size.floor(), unit)
} else {
if size < 10.0 {
format!("{:.1}{}", (size * 10.0).floor() / 10.0, unit)
} else {
format!("{}{}", size.floor(), unit)
}
}
}
fn find_byte_size_unit(size: u64) -> (f64, char) {
const UNITS: &'static str = "BKM";
let mut size = size as f64;
for unit in UNITS.chars() {
if size > 999.9 {
size /= 1024.0;
} else {
return (size, unit);
}
}
(size, 'G')
}
fn unmix(x: f32,
|
: (f32, f32)) -> f32 {
let (a, b) = range;
(x - a) / (b - a)
}
fn nan_to_zero(x: f32) -> f32 {
if x.is_nan() { 0.0 } else { x }
}
|
range
|
identifier_name
|
net.rs
|
use color::Colorf32;
use fastup::{self, Node, parse_for_first_node, parse_color};
use stats_once::{NET_DOWNLOAD_SPEED, NET_UPLOAD_SPEED};
use super::error_node;
use std::mem::swap;
#[derive(Debug, Copy, Clone, Default)]
pub struct Widget;
impl super::Widget for Widget {
fn expand(&self, args: Vec<String>) -> Node {
match args.len() {
4 | 6 => node_from_args(args),
8 => node_from_args(args), // debug only
_ => error_node("(ccdd44: net) takes 4 or 6 arguments \\(speed in KiB\\): color-cold\\|color-hot\\|lo-speed\\|hi-speed{\\|lo-speed-upload\\|hi-speed-upload}"),
}
}
}
fn node_from_args(args: Vec<String>) -> Node {
try_node_from_args(args).unwrap_or_else(|e| error_node(&e))
}
fn try_node_from_args(args: Vec<String>) -> Result<Node, String> {
assert!((args.len() == 4 || args.len() == 6) || args.len() == 8);
let cold = parse_color(&args[0]).map_err(escape_fastup)?;
let hot = parse_color(&args[1]).map_err(escape_fastup)?;
let parse_speed = |i| -> Result<Option<u64>, String> {
if args.len() <= i || args[i].trim().len() == 0 {
Ok(None)
} else {
let speed: f64 = args[i].parse().map_err(escape_fastup)?;
if speed < 0.0 {
Err(format!("speed cannot be a negative number, but got {}", speed))
} else {
Ok(Some((speed * 1024.0) as u64))
}
}
};
let lo_speed_down = parse_speed(2)?.unwrap();
let hi_speed_down = parse_speed(3)?.unwrap();
let lo_speed_up = parse_speed(4)?.unwrap_or(lo_speed_down);
let hi_speed_up = parse_speed(5)?.unwrap_or(hi_speed_down);
let speed_down = parse_speed(6)?.unwrap_or(*NET_DOWNLOAD_SPEED);
let speed_up = parse_speed(7)?.unwrap_or(*NET_UPLOAD_SPEED);
Ok(
net_node(
cold.into(),
hot.into(),
lo_speed_down,
hi_speed_down,
lo_speed_up,
hi_speed_up,
speed_down,
speed_up,
)
)
}
fn net_node(
cold: Colorf32,
hot: Colorf32,
lo_speed_down: u64,
hi_speed_down: u64,
lo_speed_up: u64,
hi_speed_up: u64,
speed_down: u64,
speed_up: u64,
) -> Node
{
const BG_LIGHTNESS: f32 = 0.15;
const FG_LIGHTNESS: f32 = 0.4;
const IDLE_LIGHTNESS: f32 = 0.2;
const FAST_LIGHTNESS_BOOST: f32 = 0.3;
const PROGRESS_INDICATORS: &'static str = "▁▂▃▄▅▆▇";
let ratio_of = |x, lo, hi| nan_to_zero(unmix(x as f32, (lo as f32, hi as f32)));
let ratio_down = ratio_of(speed_down, lo_speed_down, hi_speed_down);
let ratio_up = ratio_of(speed_up, lo_speed_up, hi_speed_up);
let (fast_speed, fast_ratio, fast_boost, boost_down, boost_up) = {
if speed_down == 0 && speed_up == 0 {
(0, 0.0, 0.0, 0.0, 0.0)
} else if (ratio_up - ratio_down).abs() < 1e-5 {
(speed_down, ratio_down, FAST_LIGHTNESS_BOOST, FAST_LIGHTNESS_BOOST, 0.0)
} else if ratio_up > ratio_down {
(speed_up, ratio_up, FAST_LIGHTNESS_BOOST, 0.0, FAST_LIGHTNESS_BOOST)
} else {
(speed_down, ratio_down, FAST_LIGHTNESS_BOOST, FAST_LIGHTNESS_BOOST, 0.0)
}
};
let fast_ratio = fast_ratio.max(0.0).min(1.0);
let ratio_down = ratio_down.max(0.0).min(1.0);
let ratio_up = ratio_up .max(0.0).min(1.0);
let bg_cold = cold.set_lightness(BG_LIGHTNESS);
let bg_hot = hot.set_lightness(BG_LIGHTNESS);
let bg = bg_cold.mix(bg_hot, fast_ratio).clamp_to_888();
let idle_for = |ratio: f32, boost: f32| {
let idle_cold = cold.set_lightness(IDLE_LIGHTNESS + boost);
let idle_hot = hot.set_lightness(IDLE_LIGHTNESS + boost);
idle_cold.mix(idle_hot, ratio).clamp_to_888()
};
let fg_for = |ratio: f32, boost: f32| {
if ratio == 0.0 {
idle_for(ratio, boost)
} else {
let fg_cold = cold.set_lightness(FG_LIGHTNESS + boost);
let fg_hot = hot.set_lightness(FG_LIGHTNESS + boost);
fg_cold.mix(fg_hot, ratio).clamp_to_888()
}
};
let indicator_for = |ratio: f32, reverse: bool| {
let len = PROGRESS_INDICATORS.chars().count() as f32;
let mut i = (len * ratio).floor();
if reverse { i = len - 1.0 - i }
let i = i.min(len - 1.0).max(0.0) as usize;
PROGRESS_INDICATORS.chars().nth(i).unwrap()
};
let styled_indicator_for = |ratio: f32, boost: f32, upside_down: bool| {
let mut fg = fg_for(ratio, boost);
let mut bg = bg;
if upside_down { swap(&mut fg, &mut bg) }
let indicator = indicator_for(ratio, upside_down);
format!("[{}:({}:{})]", bg, fg, indicator)
};
let indicator_down = styled_indicator_for(ratio_down, boost_down, true);
let indicator_up = styled_indicator_for(ratio_up, boost_up, false);
let fast_text = {
let fg_fast = fg_for(fast_ratio, fast_boost);
let text = format_byte_size(fast_speed);
let text = format!("{:>5}", text);
let text = escape_fastup(text);
format!("({}:{})", fg_fast, text)
};
let node = format!("[{}: \\ {}{}{} ]", bg, indicator_up, indicator_down, fast_text);
parse_for_first_node(&node).unwrap()
}
fn escape_fastup<T>(input: T) -> String
where T: ToString
{
fastup::escape_for_text(&input.to_string())
}
/// Format byte size into short and human readable form.
///
/// Shortness is the most important considering factor here.
/// The largest unit is 'G'.
//
// 0B
// 10B
// 100B
// 999B
// 0.9K
// 9.0K
// 10K
// 100K
//...
//
// NOTE: There are NO spaces in front of the result.
fn format_byte_size(size: u64) -> String {
let (size, unit) = find_byte_size_unit(size);
if unit == 'B' {
format!("{}{}", size.floor(), unit)
} else {
if size < 10.0 {
format!("{:.1}{}", (size * 10.0).floor() / 10.0, unit)
} else {
format!("{}{}", size.floor(), unit)
}
}
}
fn find_byte_size_unit(size: u64) -> (f64, char) {
const UNITS: &'static str = "BKM";
let mut size = size as f64;
for unit in UNITS.chars() {
if size > 999.9 {
|
return (size, unit);
}
}
(size, 'G')
}
fn unmix(x: f32, range: (f32, f32)) -> f32 {
let (a, b) = range;
(x - a) / (b - a)
}
fn nan_to_zero(x: f32) -> f32 {
if x.is_nan() { 0.0 } else { x }
}
|
size /= 1024.0;
} else {
|
conditional_block
|
process.rs
|
// @lecorref - github.com/lecorref, @geam - github.com/geam,
// @adjivas - github.com/adjivas. See the LICENSE
// file at the top-level directory of this distribution and at
// https://github.com/adjivas/krpsim
//
// This file may not be copied, modified, or distributed
// except according to those terms.
extern crate krpsim;
use self::krpsim::format::stock::inventory::Inventory;
use self::krpsim::format::stock::ressource::Ressource;
use self::krpsim::format::operate::process::Process;
#[test]
fn test_process_constructor_new() {
assert_eq!(
|
Inventory::new(
vec!(
Ressource::new("silver-rupee".to_string(), 200),
) // need
),
Inventory::new(
vec!(
Ressource::new("heart".to_string(), 10),
) // result
),
)
),
"knight:(silver-rupee:200):(heart:10):10"
);
}
|
format!("{}",
Process::from_integer(
"knight".to_string(), // name
10, // cycle
|
random_line_split
|
process.rs
|
// @lecorref - github.com/lecorref, @geam - github.com/geam,
// @adjivas - github.com/adjivas. See the LICENSE
// file at the top-level directory of this distribution and at
// https://github.com/adjivas/krpsim
//
// This file may not be copied, modified, or distributed
// except according to those terms.
extern crate krpsim;
use self::krpsim::format::stock::inventory::Inventory;
use self::krpsim::format::stock::ressource::Ressource;
use self::krpsim::format::operate::process::Process;
#[test]
fn
|
() {
assert_eq!(
format!("{}",
Process::from_integer(
"knight".to_string(), // name
10, // cycle
Inventory::new(
vec!(
Ressource::new("silver-rupee".to_string(), 200),
) // need
),
Inventory::new(
vec!(
Ressource::new("heart".to_string(), 10),
) // result
),
)
),
"knight:(silver-rupee:200):(heart:10):10"
);
}
|
test_process_constructor_new
|
identifier_name
|
process.rs
|
// @lecorref - github.com/lecorref, @geam - github.com/geam,
// @adjivas - github.com/adjivas. See the LICENSE
// file at the top-level directory of this distribution and at
// https://github.com/adjivas/krpsim
//
// This file may not be copied, modified, or distributed
// except according to those terms.
extern crate krpsim;
use self::krpsim::format::stock::inventory::Inventory;
use self::krpsim::format::stock::ressource::Ressource;
use self::krpsim::format::operate::process::Process;
#[test]
fn test_process_constructor_new()
|
}
|
{
assert_eq!(
format!("{}",
Process::from_integer(
"knight".to_string(), // name
10, // cycle
Inventory::new(
vec!(
Ressource::new("silver-rupee".to_string(), 200),
) // need
),
Inventory::new(
vec!(
Ressource::new("heart".to_string(), 10),
) // result
),
)
),
"knight:(silver-rupee:200):(heart:10):10"
);
|
identifier_body
|
resource-in-struct.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.
#![feature(managed_boxes, unsafe_destructor)]
// Ensures that class dtors run if the object is inside an enum
// variant
use std::cell::Cell;
use std::gc::{Gc, GC};
type closable = Gc<Cell<bool>>;
struct close_res {
i: closable,
}
#[unsafe_destructor]
impl Drop for close_res {
fn
|
(&mut self) {
self.i.set(false);
}
}
fn close_res(i: closable) -> close_res {
close_res {
i: i
}
}
enum option<T> { none, some(T), }
fn sink(_res: option<close_res>) { }
pub fn main() {
let c = box(GC) Cell::new(true);
sink(none);
sink(some(close_res(c)));
assert!(!c.get());
}
|
drop
|
identifier_name
|
resource-in-struct.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
|
// Ensures that class dtors run if the object is inside an enum
// variant
use std::cell::Cell;
use std::gc::{Gc, GC};
type closable = Gc<Cell<bool>>;
struct close_res {
i: closable,
}
#[unsafe_destructor]
impl Drop for close_res {
fn drop(&mut self) {
self.i.set(false);
}
}
fn close_res(i: closable) -> close_res {
close_res {
i: i
}
}
enum option<T> { none, some(T), }
fn sink(_res: option<close_res>) { }
pub fn main() {
let c = box(GC) Cell::new(true);
sink(none);
sink(some(close_res(c)));
assert!(!c.get());
}
|
// except according to those terms.
#![feature(managed_boxes, unsafe_destructor)]
|
random_line_split
|
resource-in-struct.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.
#![feature(managed_boxes, unsafe_destructor)]
// Ensures that class dtors run if the object is inside an enum
// variant
use std::cell::Cell;
use std::gc::{Gc, GC};
type closable = Gc<Cell<bool>>;
struct close_res {
i: closable,
}
#[unsafe_destructor]
impl Drop for close_res {
fn drop(&mut self) {
self.i.set(false);
}
}
fn close_res(i: closable) -> close_res
|
enum option<T> { none, some(T), }
fn sink(_res: option<close_res>) { }
pub fn main() {
let c = box(GC) Cell::new(true);
sink(none);
sink(some(close_res(c)));
assert!(!c.get());
}
|
{
close_res {
i: i
}
}
|
identifier_body
|
font.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/. */
use color::Color;
use font_context::FontContext;
use geometry::Au;
use platform::font_context::FontContextHandle;
use platform::font::{FontHandle, FontTable};
use render_context::RenderContext;
use servo_util::range::Range;
use text::glyph::{GlyphStore, GlyphIndex};
use text::shaping::ShaperMethods;
use text::{Shaper, TextRun};
use azure::{AzFloat, AzScaledFontRef};
use azure::scaled_font::ScaledFont;
use azure::azure_hl::{BackendType, ColorPattern};
use geom::{Point2D, Rect, Size2D};
// FontHandle encapsulates access to the platform's font API,
// e.g. quartz, FreeType. It provides access to metrics and tables
// needed by the text shaper as well as access to the underlying font
// resources needed by the graphics layer to draw glyphs.
pub trait FontHandleMethods {
fn new_from_buffer(fctx: &FontContextHandle, buf: ~[u8], style: &SpecifiedFontStyle)
-> Result<Self,()>;
// an identifier usable by FontContextHandle to recreate this FontHandle.
fn face_identifier(&self) -> ~str;
fn family_name(&self) -> ~str;
fn face_name(&self) -> ~str;
fn is_italic(&self) -> bool;
fn boldness(&self) -> CSSFontWeight;
fn clone_with_style(&self, fctx: &FontContextHandle, style: &UsedFontStyle)
-> Result<FontHandle, ()>;
fn glyph_index(&self, codepoint: char) -> Option<GlyphIndex>;
fn glyph_h_advance(&self, GlyphIndex) -> Option<FractionalPixel>;
fn get_metrics(&self) -> FontMetrics;
fn get_table_for_tag(&self, FontTableTag) -> Option<FontTable>;
}
// Used to abstract over the shaper's choice of fixed int representation.
pub type FractionalPixel = float;
pub type FontTableTag = u32;
trait FontTableTagConversions {
pub fn tag_to_str(&self) -> ~str;
}
impl FontTableTagConversions for FontTableTag {
pub fn
|
(&self) -> ~str {
unsafe {
let reversed = str::raw::from_buf_len(cast::transmute(self), 4);
return str::from_chars([reversed.char_at(3),
reversed.char_at(2),
reversed.char_at(1),
reversed.char_at(0)]);
}
}
}
pub trait FontTableMethods {
fn with_buffer(&self, &fn(*u8, uint));
}
pub struct FontMetrics {
underline_size: Au,
underline_offset: Au,
leading: Au,
x_height: Au,
em_size: Au,
ascent: Au,
descent: Au,
max_advance: Au
}
// TODO(Issue #200): use enum from CSS bindings for 'font-weight'
#[deriving(Eq)]
pub enum CSSFontWeight {
FontWeight100,
FontWeight200,
FontWeight300,
FontWeight400,
FontWeight500,
FontWeight600,
FontWeight700,
FontWeight800,
FontWeight900,
}
pub impl CSSFontWeight {
pub fn is_bold(self) -> bool {
match self {
FontWeight900 | FontWeight800 | FontWeight700 | FontWeight600 => true,
_ => false
}
}
}
// TODO(Issue #179): eventually this will be split into the specified
// and used font styles. specified contains uninterpreted CSS font
// property values, while 'used' is attached to gfx::Font to descript
// the instance's properties.
//
// For now, the cases are differentiated with a typedef
#[deriving(Eq)]
pub struct FontStyle {
pt_size: float,
weight: CSSFontWeight,
italic: bool,
oblique: bool,
families: ~str,
// TODO(Issue #198): font-stretch, text-decoration, font-variant, size-adjust
}
pub type SpecifiedFontStyle = FontStyle;
pub type UsedFontStyle = FontStyle;
// FIXME: move me to layout
struct ResolvedFont {
group: @FontGroup,
style: SpecifiedFontStyle,
}
// FontDescriptor serializes a specific font and used font style
// options, such as point size.
// It's used to swizzle/unswizzle gfx::Font instances when
// communicating across tasks, such as the display list between layout
// and render tasks.
#[deriving(Eq)]
pub struct FontDescriptor {
style: UsedFontStyle,
selector: FontSelector,
}
pub impl FontDescriptor {
fn new(style: UsedFontStyle, selector: FontSelector) -> FontDescriptor {
FontDescriptor {
style: style,
selector: selector,
}
}
}
// A FontSelector is a platform-specific strategy for serializing face names.
#[deriving(Eq)]
pub enum FontSelector {
SelectorPlatformIdentifier(~str),
}
// This struct is the result of mapping a specified FontStyle into the
// available fonts on the system. It contains an ordered list of font
// instances to be used in case the prior font cannot be used for
// rendering the specified language.
// The ordering of font instances is mainly decided by the CSS
// 'font-family' property. The last font is a system fallback font.
pub struct FontGroup {
families: @str,
// style of the first western font in group, which is
// used for purposes of calculating text run metrics.
style: UsedFontStyle,
fonts: ~[@mut Font],
}
pub impl FontGroup {
fn new(families: @str, style: &UsedFontStyle, fonts: ~[@mut Font]) -> FontGroup {
FontGroup {
families: families,
style: copy *style,
fonts: fonts,
}
}
fn create_textrun(&self, text: ~str) -> TextRun {
assert!(self.fonts.len() > 0);
// TODO(Issue #177): Actually fall back through the FontGroup when a font is unsuitable.
return TextRun::new(self.fonts[0], text);
}
}
pub struct RunMetrics {
// may be negative due to negative width (i.e., kerning of '.' in 'P.T.')
advance_width: Au,
ascent: Au, // nonzero
descent: Au, // nonzero
// this bounding box is relative to the left origin baseline.
// so, bounding_box.position.y = -ascent
bounding_box: Rect<Au>
}
/**
A font instance. Layout can use this to calculate glyph metrics
and the renderer can use it to render text.
*/
pub struct Font {
priv handle: FontHandle,
priv azure_font: Option<ScaledFont>,
priv shaper: Option<@Shaper>,
style: UsedFontStyle,
metrics: FontMetrics,
backend: BackendType,
}
pub impl Font {
fn new_from_buffer(ctx: &FontContext,
buffer: ~[u8],
style: &SpecifiedFontStyle,
backend: BackendType)
-> Result<@mut Font, ()> {
let handle = FontHandleMethods::new_from_buffer(&ctx.handle, buffer, style);
let handle: FontHandle = if handle.is_ok() {
result::unwrap(handle)
} else {
return Err(handle.get_err());
};
let metrics = handle.get_metrics();
// TODO(Issue #179): convert between specified and used font style here?
return Ok(@mut Font {
handle: handle,
azure_font: None,
shaper: None,
style: copy *style,
metrics: metrics,
backend: backend,
});
}
fn new_from_adopted_handle(_fctx: &FontContext, handle: FontHandle,
style: &SpecifiedFontStyle, backend: BackendType) -> @mut Font {
let metrics = handle.get_metrics();
@mut Font {
handle: handle,
azure_font: None,
shaper: None,
style: copy *style,
metrics: metrics,
backend: backend,
}
}
fn new_from_existing_handle(fctx: &FontContext, handle: &FontHandle,
style: &SpecifiedFontStyle, backend: BackendType) -> Result<@mut Font,()> {
// TODO(Issue #179): convert between specified and used font style here?
let styled_handle = match handle.clone_with_style(&fctx.handle, style) {
Ok(result) => result,
Err(()) => return Err(())
};
return Ok(Font::new_from_adopted_handle(fctx, styled_handle, style, backend));
}
priv fn get_shaper(@mut self) -> @Shaper {
// fast path: already created a shaper
match self.shaper {
Some(shaper) => { return shaper; },
None => {}
}
let shaper = @Shaper::new(self);
self.shaper = Some(shaper);
shaper
}
fn get_table_for_tag(&self, tag: FontTableTag) -> Option<FontTable> {
let result = self.handle.get_table_for_tag(tag);
let status = if result.is_some() { "Found" } else { "Didn't find" };
debug!("%s font table[%s] with family=%s, face=%s",
status, tag.tag_to_str(),
self.handle.family_name(), self.handle.face_name());
return result;
}
// TODO: this should return a borrowed pointer, but I can't figure
// out why borrowck doesn't like my implementation.
priv fn get_azure_font(&mut self) -> AzScaledFontRef {
// fast path: we've already created the azure font resource
match self.azure_font {
Some(ref azfont) => return azfont.get_ref(),
None => {}
}
let scaled_font = self.create_azure_font();
self.azure_font = Some(scaled_font);
// try again.
return self.get_azure_font();
}
#[cfg(target_os="macos")]
priv fn create_azure_font(&mut self) -> ScaledFont {
let cg_font = self.handle.get_CGFont();
let size = self.style.pt_size as AzFloat;
ScaledFont::new(self.backend, &cg_font, size)
}
#[cfg(target_os="linux")]
priv fn create_azure_font(&self) -> ScaledFont {
let freetype_font = self.handle.face;
let size = self.style.pt_size as AzFloat;
ScaledFont::new(self.backend, freetype_font, size)
}
}
pub impl Font {
fn draw_text_into_context(&mut self,
rctx: &RenderContext,
run: &TextRun,
range: &Range,
baseline_origin: Point2D<Au>,
color: Color) {
use core::libc::types::common::c99::{uint16_t, uint32_t};
use azure::{struct__AzDrawOptions,
struct__AzGlyph,
struct__AzGlyphBuffer,
struct__AzPoint};
use azure::azure::bindgen::{AzDrawTargetFillGlyphs};
let target = rctx.get_draw_target();
let azfontref = self.get_azure_font();
let pattern = ColorPattern(color);
let azure_pattern = pattern.azure_color_pattern;
assert!(azure_pattern.is_not_null());
let options = struct__AzDrawOptions {
mAlpha: 1f as AzFloat,
fields: 0x0200 as uint16_t
};
let mut origin = copy baseline_origin;
let mut azglyphs = ~[];
vec::reserve(&mut azglyphs, range.length());
for run.glyphs.iter_glyphs_for_char_range(range) |_i, glyph| {
let glyph_advance = glyph.advance();
let glyph_offset = glyph.offset().get_or_default(Au::zero_point());
let azglyph = struct__AzGlyph {
mIndex: glyph.index() as uint32_t,
mPosition: struct__AzPoint {
x: (origin.x + glyph_offset.x).to_px() as AzFloat,
y: (origin.y + glyph_offset.y).to_px() as AzFloat
}
};
origin = Point2D(origin.x + glyph_advance, origin.y);
azglyphs.push(azglyph)
};
let azglyph_buf_len = azglyphs.len();
if azglyph_buf_len == 0 { return; } // Otherwise the Quartz backend will assert.
let glyphbuf = unsafe {
struct__AzGlyphBuffer {
mGlyphs: vec::raw::to_ptr(azglyphs),
mNumGlyphs: azglyph_buf_len as uint32_t
}
};
// TODO(Issue #64): this call needs to move into azure_hl.rs
AzDrawTargetFillGlyphs(target.azure_draw_target,
azfontref,
ptr::to_unsafe_ptr(&glyphbuf),
azure_pattern,
ptr::to_unsafe_ptr(&options),
ptr::null());
}
fn measure_text(&self, run: &TextRun, range: &Range) -> RunMetrics {
// TODO(Issue #199): alter advance direction for RTL
// TODO(Issue #98): using inter-char and inter-word spacing settings when measuring text
let mut advance = Au(0);
for run.glyphs.iter_glyphs_for_char_range(range) |_i, glyph| {
advance += glyph.advance();
}
let bounds = Rect(Point2D(Au(0), -self.metrics.ascent),
Size2D(advance, self.metrics.ascent + self.metrics.descent));
// TODO(Issue #125): support loose and tight bounding boxes; using the
// ascent+descent and advance is sometimes too generous and
// looking at actual glyph extents can yield a tighter box.
RunMetrics {
advance_width: advance,
bounding_box: bounds,
ascent: self.metrics.ascent,
descent: self.metrics.descent,
}
}
fn shape_text(@mut self, text: &str, store: &mut GlyphStore) {
// TODO(Issue #229): use a more efficient strategy for repetitive shaping.
// For example, Gecko uses a per-"word" hashtable of shaper results.
let shaper = self.get_shaper();
shaper.shape_text(text, store);
}
fn get_descriptor(&self) -> FontDescriptor {
FontDescriptor::new(copy self.style, SelectorPlatformIdentifier(self.handle.face_identifier()))
}
fn glyph_index(&self, codepoint: char) -> Option<GlyphIndex> {
self.handle.glyph_index(codepoint)
}
fn glyph_h_advance(&self, glyph: GlyphIndex) -> FractionalPixel {
match self.handle.glyph_h_advance(glyph) {
Some(adv) => adv,
None => /* FIXME: Need fallback strategy */ 10f as FractionalPixel
}
}
}
/*fn should_destruct_on_fail_without_leaking() {
#[test];
#[should_fail];
let fctx = @FontContext();
let matcher = @FontMatcher(fctx);
let _font = matcher.get_test_font();
fail;
}
fn should_get_glyph_indexes() {
#[test];
let fctx = @FontContext();
let matcher = @FontMatcher(fctx);
let font = matcher.get_test_font();
let glyph_idx = font.glyph_index('w');
assert!(glyph_idx == Some(40u as GlyphIndex));
}
fn should_get_glyph_advance() {
#[test];
#[ignore];
let fctx = @FontContext();
let matcher = @FontMatcher(fctx);
let font = matcher.get_test_font();
let x = font.glyph_h_advance(40u as GlyphIndex);
assert!(x == 15f || x == 16f);
}
// Testing thread safety
fn should_get_glyph_advance_stress() {
#[test];
#[ignore];
let mut ports = ~[];
for iter::repeat(100) {
let (chan, port) = pipes::stream();
ports += [@port];
do task::spawn {
let fctx = @FontContext();
let matcher = @FontMatcher(fctx);
let _font = matcher.get_test_font();
let x = font.glyph_h_advance(40u as GlyphIndex);
assert!(x == 15f || x == 16f);
chan.send(());
}
}
for ports.each |port| {
port.recv();
}
}
fn should_be_able_to_create_instances_in_multiple_threads() {
#[test];
for iter::repeat(10u) {
do task::spawn {
let fctx = @FontContext();
let matcher = @FontMatcher(fctx);
let _font = matcher.get_test_font();
}
}
}
*/
|
tag_to_str
|
identifier_name
|
font.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/. */
use color::Color;
use font_context::FontContext;
use geometry::Au;
use platform::font_context::FontContextHandle;
use platform::font::{FontHandle, FontTable};
use render_context::RenderContext;
use servo_util::range::Range;
use text::glyph::{GlyphStore, GlyphIndex};
use text::shaping::ShaperMethods;
use text::{Shaper, TextRun};
use azure::{AzFloat, AzScaledFontRef};
use azure::scaled_font::ScaledFont;
use azure::azure_hl::{BackendType, ColorPattern};
use geom::{Point2D, Rect, Size2D};
// FontHandle encapsulates access to the platform's font API,
// e.g. quartz, FreeType. It provides access to metrics and tables
// needed by the text shaper as well as access to the underlying font
// resources needed by the graphics layer to draw glyphs.
pub trait FontHandleMethods {
fn new_from_buffer(fctx: &FontContextHandle, buf: ~[u8], style: &SpecifiedFontStyle)
-> Result<Self,()>;
// an identifier usable by FontContextHandle to recreate this FontHandle.
fn face_identifier(&self) -> ~str;
fn family_name(&self) -> ~str;
fn face_name(&self) -> ~str;
fn is_italic(&self) -> bool;
fn boldness(&self) -> CSSFontWeight;
fn clone_with_style(&self, fctx: &FontContextHandle, style: &UsedFontStyle)
-> Result<FontHandle, ()>;
fn glyph_index(&self, codepoint: char) -> Option<GlyphIndex>;
fn glyph_h_advance(&self, GlyphIndex) -> Option<FractionalPixel>;
fn get_metrics(&self) -> FontMetrics;
fn get_table_for_tag(&self, FontTableTag) -> Option<FontTable>;
}
// Used to abstract over the shaper's choice of fixed int representation.
pub type FractionalPixel = float;
pub type FontTableTag = u32;
trait FontTableTagConversions {
pub fn tag_to_str(&self) -> ~str;
}
impl FontTableTagConversions for FontTableTag {
pub fn tag_to_str(&self) -> ~str {
unsafe {
let reversed = str::raw::from_buf_len(cast::transmute(self), 4);
return str::from_chars([reversed.char_at(3),
reversed.char_at(2),
reversed.char_at(1),
reversed.char_at(0)]);
}
}
}
pub trait FontTableMethods {
fn with_buffer(&self, &fn(*u8, uint));
}
pub struct FontMetrics {
underline_size: Au,
underline_offset: Au,
leading: Au,
x_height: Au,
em_size: Au,
ascent: Au,
descent: Au,
max_advance: Au
}
// TODO(Issue #200): use enum from CSS bindings for 'font-weight'
#[deriving(Eq)]
pub enum CSSFontWeight {
FontWeight100,
FontWeight200,
FontWeight300,
FontWeight400,
FontWeight500,
FontWeight600,
FontWeight700,
FontWeight800,
FontWeight900,
}
pub impl CSSFontWeight {
pub fn is_bold(self) -> bool {
match self {
FontWeight900 | FontWeight800 | FontWeight700 | FontWeight600 => true,
_ => false
}
}
}
// TODO(Issue #179): eventually this will be split into the specified
// and used font styles. specified contains uninterpreted CSS font
// property values, while 'used' is attached to gfx::Font to descript
// the instance's properties.
//
// For now, the cases are differentiated with a typedef
#[deriving(Eq)]
pub struct FontStyle {
pt_size: float,
weight: CSSFontWeight,
italic: bool,
oblique: bool,
families: ~str,
// TODO(Issue #198): font-stretch, text-decoration, font-variant, size-adjust
}
pub type SpecifiedFontStyle = FontStyle;
pub type UsedFontStyle = FontStyle;
// FIXME: move me to layout
struct ResolvedFont {
group: @FontGroup,
style: SpecifiedFontStyle,
}
// FontDescriptor serializes a specific font and used font style
// options, such as point size.
// It's used to swizzle/unswizzle gfx::Font instances when
// communicating across tasks, such as the display list between layout
// and render tasks.
#[deriving(Eq)]
pub struct FontDescriptor {
style: UsedFontStyle,
selector: FontSelector,
}
pub impl FontDescriptor {
fn new(style: UsedFontStyle, selector: FontSelector) -> FontDescriptor {
FontDescriptor {
style: style,
selector: selector,
}
}
}
// A FontSelector is a platform-specific strategy for serializing face names.
#[deriving(Eq)]
pub enum FontSelector {
SelectorPlatformIdentifier(~str),
}
// This struct is the result of mapping a specified FontStyle into the
// available fonts on the system. It contains an ordered list of font
// instances to be used in case the prior font cannot be used for
// rendering the specified language.
|
// The ordering of font instances is mainly decided by the CSS
// 'font-family' property. The last font is a system fallback font.
pub struct FontGroup {
families: @str,
// style of the first western font in group, which is
// used for purposes of calculating text run metrics.
style: UsedFontStyle,
fonts: ~[@mut Font],
}
pub impl FontGroup {
fn new(families: @str, style: &UsedFontStyle, fonts: ~[@mut Font]) -> FontGroup {
FontGroup {
families: families,
style: copy *style,
fonts: fonts,
}
}
fn create_textrun(&self, text: ~str) -> TextRun {
assert!(self.fonts.len() > 0);
// TODO(Issue #177): Actually fall back through the FontGroup when a font is unsuitable.
return TextRun::new(self.fonts[0], text);
}
}
pub struct RunMetrics {
// may be negative due to negative width (i.e., kerning of '.' in 'P.T.')
advance_width: Au,
ascent: Au, // nonzero
descent: Au, // nonzero
// this bounding box is relative to the left origin baseline.
// so, bounding_box.position.y = -ascent
bounding_box: Rect<Au>
}
/**
A font instance. Layout can use this to calculate glyph metrics
and the renderer can use it to render text.
*/
pub struct Font {
priv handle: FontHandle,
priv azure_font: Option<ScaledFont>,
priv shaper: Option<@Shaper>,
style: UsedFontStyle,
metrics: FontMetrics,
backend: BackendType,
}
pub impl Font {
fn new_from_buffer(ctx: &FontContext,
buffer: ~[u8],
style: &SpecifiedFontStyle,
backend: BackendType)
-> Result<@mut Font, ()> {
let handle = FontHandleMethods::new_from_buffer(&ctx.handle, buffer, style);
let handle: FontHandle = if handle.is_ok() {
result::unwrap(handle)
} else {
return Err(handle.get_err());
};
let metrics = handle.get_metrics();
// TODO(Issue #179): convert between specified and used font style here?
return Ok(@mut Font {
handle: handle,
azure_font: None,
shaper: None,
style: copy *style,
metrics: metrics,
backend: backend,
});
}
fn new_from_adopted_handle(_fctx: &FontContext, handle: FontHandle,
style: &SpecifiedFontStyle, backend: BackendType) -> @mut Font {
let metrics = handle.get_metrics();
@mut Font {
handle: handle,
azure_font: None,
shaper: None,
style: copy *style,
metrics: metrics,
backend: backend,
}
}
fn new_from_existing_handle(fctx: &FontContext, handle: &FontHandle,
style: &SpecifiedFontStyle, backend: BackendType) -> Result<@mut Font,()> {
// TODO(Issue #179): convert between specified and used font style here?
let styled_handle = match handle.clone_with_style(&fctx.handle, style) {
Ok(result) => result,
Err(()) => return Err(())
};
return Ok(Font::new_from_adopted_handle(fctx, styled_handle, style, backend));
}
priv fn get_shaper(@mut self) -> @Shaper {
// fast path: already created a shaper
match self.shaper {
Some(shaper) => { return shaper; },
None => {}
}
let shaper = @Shaper::new(self);
self.shaper = Some(shaper);
shaper
}
fn get_table_for_tag(&self, tag: FontTableTag) -> Option<FontTable> {
let result = self.handle.get_table_for_tag(tag);
let status = if result.is_some() { "Found" } else { "Didn't find" };
debug!("%s font table[%s] with family=%s, face=%s",
status, tag.tag_to_str(),
self.handle.family_name(), self.handle.face_name());
return result;
}
// TODO: this should return a borrowed pointer, but I can't figure
// out why borrowck doesn't like my implementation.
priv fn get_azure_font(&mut self) -> AzScaledFontRef {
// fast path: we've already created the azure font resource
match self.azure_font {
Some(ref azfont) => return azfont.get_ref(),
None => {}
}
let scaled_font = self.create_azure_font();
self.azure_font = Some(scaled_font);
// try again.
return self.get_azure_font();
}
#[cfg(target_os="macos")]
priv fn create_azure_font(&mut self) -> ScaledFont {
let cg_font = self.handle.get_CGFont();
let size = self.style.pt_size as AzFloat;
ScaledFont::new(self.backend, &cg_font, size)
}
#[cfg(target_os="linux")]
priv fn create_azure_font(&self) -> ScaledFont {
let freetype_font = self.handle.face;
let size = self.style.pt_size as AzFloat;
ScaledFont::new(self.backend, freetype_font, size)
}
}
pub impl Font {
fn draw_text_into_context(&mut self,
rctx: &RenderContext,
run: &TextRun,
range: &Range,
baseline_origin: Point2D<Au>,
color: Color) {
use core::libc::types::common::c99::{uint16_t, uint32_t};
use azure::{struct__AzDrawOptions,
struct__AzGlyph,
struct__AzGlyphBuffer,
struct__AzPoint};
use azure::azure::bindgen::{AzDrawTargetFillGlyphs};
let target = rctx.get_draw_target();
let azfontref = self.get_azure_font();
let pattern = ColorPattern(color);
let azure_pattern = pattern.azure_color_pattern;
assert!(azure_pattern.is_not_null());
let options = struct__AzDrawOptions {
mAlpha: 1f as AzFloat,
fields: 0x0200 as uint16_t
};
let mut origin = copy baseline_origin;
let mut azglyphs = ~[];
vec::reserve(&mut azglyphs, range.length());
for run.glyphs.iter_glyphs_for_char_range(range) |_i, glyph| {
let glyph_advance = glyph.advance();
let glyph_offset = glyph.offset().get_or_default(Au::zero_point());
let azglyph = struct__AzGlyph {
mIndex: glyph.index() as uint32_t,
mPosition: struct__AzPoint {
x: (origin.x + glyph_offset.x).to_px() as AzFloat,
y: (origin.y + glyph_offset.y).to_px() as AzFloat
}
};
origin = Point2D(origin.x + glyph_advance, origin.y);
azglyphs.push(azglyph)
};
let azglyph_buf_len = azglyphs.len();
if azglyph_buf_len == 0 { return; } // Otherwise the Quartz backend will assert.
let glyphbuf = unsafe {
struct__AzGlyphBuffer {
mGlyphs: vec::raw::to_ptr(azglyphs),
mNumGlyphs: azglyph_buf_len as uint32_t
}
};
// TODO(Issue #64): this call needs to move into azure_hl.rs
AzDrawTargetFillGlyphs(target.azure_draw_target,
azfontref,
ptr::to_unsafe_ptr(&glyphbuf),
azure_pattern,
ptr::to_unsafe_ptr(&options),
ptr::null());
}
fn measure_text(&self, run: &TextRun, range: &Range) -> RunMetrics {
// TODO(Issue #199): alter advance direction for RTL
// TODO(Issue #98): using inter-char and inter-word spacing settings when measuring text
let mut advance = Au(0);
for run.glyphs.iter_glyphs_for_char_range(range) |_i, glyph| {
advance += glyph.advance();
}
let bounds = Rect(Point2D(Au(0), -self.metrics.ascent),
Size2D(advance, self.metrics.ascent + self.metrics.descent));
// TODO(Issue #125): support loose and tight bounding boxes; using the
// ascent+descent and advance is sometimes too generous and
// looking at actual glyph extents can yield a tighter box.
RunMetrics {
advance_width: advance,
bounding_box: bounds,
ascent: self.metrics.ascent,
descent: self.metrics.descent,
}
}
fn shape_text(@mut self, text: &str, store: &mut GlyphStore) {
// TODO(Issue #229): use a more efficient strategy for repetitive shaping.
// For example, Gecko uses a per-"word" hashtable of shaper results.
let shaper = self.get_shaper();
shaper.shape_text(text, store);
}
fn get_descriptor(&self) -> FontDescriptor {
FontDescriptor::new(copy self.style, SelectorPlatformIdentifier(self.handle.face_identifier()))
}
fn glyph_index(&self, codepoint: char) -> Option<GlyphIndex> {
self.handle.glyph_index(codepoint)
}
fn glyph_h_advance(&self, glyph: GlyphIndex) -> FractionalPixel {
match self.handle.glyph_h_advance(glyph) {
Some(adv) => adv,
None => /* FIXME: Need fallback strategy */ 10f as FractionalPixel
}
}
}
/*fn should_destruct_on_fail_without_leaking() {
#[test];
#[should_fail];
let fctx = @FontContext();
let matcher = @FontMatcher(fctx);
let _font = matcher.get_test_font();
fail;
}
fn should_get_glyph_indexes() {
#[test];
let fctx = @FontContext();
let matcher = @FontMatcher(fctx);
let font = matcher.get_test_font();
let glyph_idx = font.glyph_index('w');
assert!(glyph_idx == Some(40u as GlyphIndex));
}
fn should_get_glyph_advance() {
#[test];
#[ignore];
let fctx = @FontContext();
let matcher = @FontMatcher(fctx);
let font = matcher.get_test_font();
let x = font.glyph_h_advance(40u as GlyphIndex);
assert!(x == 15f || x == 16f);
}
// Testing thread safety
fn should_get_glyph_advance_stress() {
#[test];
#[ignore];
let mut ports = ~[];
for iter::repeat(100) {
let (chan, port) = pipes::stream();
ports += [@port];
do task::spawn {
let fctx = @FontContext();
let matcher = @FontMatcher(fctx);
let _font = matcher.get_test_font();
let x = font.glyph_h_advance(40u as GlyphIndex);
assert!(x == 15f || x == 16f);
chan.send(());
}
}
for ports.each |port| {
port.recv();
}
}
fn should_be_able_to_create_instances_in_multiple_threads() {
#[test];
for iter::repeat(10u) {
do task::spawn {
let fctx = @FontContext();
let matcher = @FontMatcher(fctx);
let _font = matcher.get_test_font();
}
}
}
*/
|
random_line_split
|
|
font.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/. */
use color::Color;
use font_context::FontContext;
use geometry::Au;
use platform::font_context::FontContextHandle;
use platform::font::{FontHandle, FontTable};
use render_context::RenderContext;
use servo_util::range::Range;
use text::glyph::{GlyphStore, GlyphIndex};
use text::shaping::ShaperMethods;
use text::{Shaper, TextRun};
use azure::{AzFloat, AzScaledFontRef};
use azure::scaled_font::ScaledFont;
use azure::azure_hl::{BackendType, ColorPattern};
use geom::{Point2D, Rect, Size2D};
// FontHandle encapsulates access to the platform's font API,
// e.g. quartz, FreeType. It provides access to metrics and tables
// needed by the text shaper as well as access to the underlying font
// resources needed by the graphics layer to draw glyphs.
pub trait FontHandleMethods {
fn new_from_buffer(fctx: &FontContextHandle, buf: ~[u8], style: &SpecifiedFontStyle)
-> Result<Self,()>;
// an identifier usable by FontContextHandle to recreate this FontHandle.
fn face_identifier(&self) -> ~str;
fn family_name(&self) -> ~str;
fn face_name(&self) -> ~str;
fn is_italic(&self) -> bool;
fn boldness(&self) -> CSSFontWeight;
fn clone_with_style(&self, fctx: &FontContextHandle, style: &UsedFontStyle)
-> Result<FontHandle, ()>;
fn glyph_index(&self, codepoint: char) -> Option<GlyphIndex>;
fn glyph_h_advance(&self, GlyphIndex) -> Option<FractionalPixel>;
fn get_metrics(&self) -> FontMetrics;
fn get_table_for_tag(&self, FontTableTag) -> Option<FontTable>;
}
// Used to abstract over the shaper's choice of fixed int representation.
pub type FractionalPixel = float;
pub type FontTableTag = u32;
trait FontTableTagConversions {
pub fn tag_to_str(&self) -> ~str;
}
impl FontTableTagConversions for FontTableTag {
pub fn tag_to_str(&self) -> ~str {
unsafe {
let reversed = str::raw::from_buf_len(cast::transmute(self), 4);
return str::from_chars([reversed.char_at(3),
reversed.char_at(2),
reversed.char_at(1),
reversed.char_at(0)]);
}
}
}
pub trait FontTableMethods {
fn with_buffer(&self, &fn(*u8, uint));
}
pub struct FontMetrics {
underline_size: Au,
underline_offset: Au,
leading: Au,
x_height: Au,
em_size: Au,
ascent: Au,
descent: Au,
max_advance: Au
}
// TODO(Issue #200): use enum from CSS bindings for 'font-weight'
#[deriving(Eq)]
pub enum CSSFontWeight {
FontWeight100,
FontWeight200,
FontWeight300,
FontWeight400,
FontWeight500,
FontWeight600,
FontWeight700,
FontWeight800,
FontWeight900,
}
pub impl CSSFontWeight {
pub fn is_bold(self) -> bool {
match self {
FontWeight900 | FontWeight800 | FontWeight700 | FontWeight600 => true,
_ => false
}
}
}
// TODO(Issue #179): eventually this will be split into the specified
// and used font styles. specified contains uninterpreted CSS font
// property values, while 'used' is attached to gfx::Font to descript
// the instance's properties.
//
// For now, the cases are differentiated with a typedef
#[deriving(Eq)]
pub struct FontStyle {
pt_size: float,
weight: CSSFontWeight,
italic: bool,
oblique: bool,
families: ~str,
// TODO(Issue #198): font-stretch, text-decoration, font-variant, size-adjust
}
pub type SpecifiedFontStyle = FontStyle;
pub type UsedFontStyle = FontStyle;
// FIXME: move me to layout
struct ResolvedFont {
group: @FontGroup,
style: SpecifiedFontStyle,
}
// FontDescriptor serializes a specific font and used font style
// options, such as point size.
// It's used to swizzle/unswizzle gfx::Font instances when
// communicating across tasks, such as the display list between layout
// and render tasks.
#[deriving(Eq)]
pub struct FontDescriptor {
style: UsedFontStyle,
selector: FontSelector,
}
pub impl FontDescriptor {
fn new(style: UsedFontStyle, selector: FontSelector) -> FontDescriptor {
FontDescriptor {
style: style,
selector: selector,
}
}
}
// A FontSelector is a platform-specific strategy for serializing face names.
#[deriving(Eq)]
pub enum FontSelector {
SelectorPlatformIdentifier(~str),
}
// This struct is the result of mapping a specified FontStyle into the
// available fonts on the system. It contains an ordered list of font
// instances to be used in case the prior font cannot be used for
// rendering the specified language.
// The ordering of font instances is mainly decided by the CSS
// 'font-family' property. The last font is a system fallback font.
pub struct FontGroup {
families: @str,
// style of the first western font in group, which is
// used for purposes of calculating text run metrics.
style: UsedFontStyle,
fonts: ~[@mut Font],
}
pub impl FontGroup {
fn new(families: @str, style: &UsedFontStyle, fonts: ~[@mut Font]) -> FontGroup {
FontGroup {
families: families,
style: copy *style,
fonts: fonts,
}
}
fn create_textrun(&self, text: ~str) -> TextRun {
assert!(self.fonts.len() > 0);
// TODO(Issue #177): Actually fall back through the FontGroup when a font is unsuitable.
return TextRun::new(self.fonts[0], text);
}
}
pub struct RunMetrics {
// may be negative due to negative width (i.e., kerning of '.' in 'P.T.')
advance_width: Au,
ascent: Au, // nonzero
descent: Au, // nonzero
// this bounding box is relative to the left origin baseline.
// so, bounding_box.position.y = -ascent
bounding_box: Rect<Au>
}
/**
A font instance. Layout can use this to calculate glyph metrics
and the renderer can use it to render text.
*/
pub struct Font {
priv handle: FontHandle,
priv azure_font: Option<ScaledFont>,
priv shaper: Option<@Shaper>,
style: UsedFontStyle,
metrics: FontMetrics,
backend: BackendType,
}
pub impl Font {
fn new_from_buffer(ctx: &FontContext,
buffer: ~[u8],
style: &SpecifiedFontStyle,
backend: BackendType)
-> Result<@mut Font, ()> {
let handle = FontHandleMethods::new_from_buffer(&ctx.handle, buffer, style);
let handle: FontHandle = if handle.is_ok() {
result::unwrap(handle)
} else {
return Err(handle.get_err());
};
let metrics = handle.get_metrics();
// TODO(Issue #179): convert between specified and used font style here?
return Ok(@mut Font {
handle: handle,
azure_font: None,
shaper: None,
style: copy *style,
metrics: metrics,
backend: backend,
});
}
fn new_from_adopted_handle(_fctx: &FontContext, handle: FontHandle,
style: &SpecifiedFontStyle, backend: BackendType) -> @mut Font {
let metrics = handle.get_metrics();
@mut Font {
handle: handle,
azure_font: None,
shaper: None,
style: copy *style,
metrics: metrics,
backend: backend,
}
}
fn new_from_existing_handle(fctx: &FontContext, handle: &FontHandle,
style: &SpecifiedFontStyle, backend: BackendType) -> Result<@mut Font,()> {
// TODO(Issue #179): convert between specified and used font style here?
let styled_handle = match handle.clone_with_style(&fctx.handle, style) {
Ok(result) => result,
Err(()) => return Err(())
};
return Ok(Font::new_from_adopted_handle(fctx, styled_handle, style, backend));
}
priv fn get_shaper(@mut self) -> @Shaper {
// fast path: already created a shaper
match self.shaper {
Some(shaper) => { return shaper; },
None => {}
}
let shaper = @Shaper::new(self);
self.shaper = Some(shaper);
shaper
}
fn get_table_for_tag(&self, tag: FontTableTag) -> Option<FontTable> {
let result = self.handle.get_table_for_tag(tag);
let status = if result.is_some() { "Found" } else { "Didn't find" };
debug!("%s font table[%s] with family=%s, face=%s",
status, tag.tag_to_str(),
self.handle.family_name(), self.handle.face_name());
return result;
}
// TODO: this should return a borrowed pointer, but I can't figure
// out why borrowck doesn't like my implementation.
priv fn get_azure_font(&mut self) -> AzScaledFontRef {
// fast path: we've already created the azure font resource
match self.azure_font {
Some(ref azfont) => return azfont.get_ref(),
None => {}
}
let scaled_font = self.create_azure_font();
self.azure_font = Some(scaled_font);
// try again.
return self.get_azure_font();
}
#[cfg(target_os="macos")]
priv fn create_azure_font(&mut self) -> ScaledFont
|
#[cfg(target_os="linux")]
priv fn create_azure_font(&self) -> ScaledFont {
let freetype_font = self.handle.face;
let size = self.style.pt_size as AzFloat;
ScaledFont::new(self.backend, freetype_font, size)
}
}
pub impl Font {
fn draw_text_into_context(&mut self,
rctx: &RenderContext,
run: &TextRun,
range: &Range,
baseline_origin: Point2D<Au>,
color: Color) {
use core::libc::types::common::c99::{uint16_t, uint32_t};
use azure::{struct__AzDrawOptions,
struct__AzGlyph,
struct__AzGlyphBuffer,
struct__AzPoint};
use azure::azure::bindgen::{AzDrawTargetFillGlyphs};
let target = rctx.get_draw_target();
let azfontref = self.get_azure_font();
let pattern = ColorPattern(color);
let azure_pattern = pattern.azure_color_pattern;
assert!(azure_pattern.is_not_null());
let options = struct__AzDrawOptions {
mAlpha: 1f as AzFloat,
fields: 0x0200 as uint16_t
};
let mut origin = copy baseline_origin;
let mut azglyphs = ~[];
vec::reserve(&mut azglyphs, range.length());
for run.glyphs.iter_glyphs_for_char_range(range) |_i, glyph| {
let glyph_advance = glyph.advance();
let glyph_offset = glyph.offset().get_or_default(Au::zero_point());
let azglyph = struct__AzGlyph {
mIndex: glyph.index() as uint32_t,
mPosition: struct__AzPoint {
x: (origin.x + glyph_offset.x).to_px() as AzFloat,
y: (origin.y + glyph_offset.y).to_px() as AzFloat
}
};
origin = Point2D(origin.x + glyph_advance, origin.y);
azglyphs.push(azglyph)
};
let azglyph_buf_len = azglyphs.len();
if azglyph_buf_len == 0 { return; } // Otherwise the Quartz backend will assert.
let glyphbuf = unsafe {
struct__AzGlyphBuffer {
mGlyphs: vec::raw::to_ptr(azglyphs),
mNumGlyphs: azglyph_buf_len as uint32_t
}
};
// TODO(Issue #64): this call needs to move into azure_hl.rs
AzDrawTargetFillGlyphs(target.azure_draw_target,
azfontref,
ptr::to_unsafe_ptr(&glyphbuf),
azure_pattern,
ptr::to_unsafe_ptr(&options),
ptr::null());
}
fn measure_text(&self, run: &TextRun, range: &Range) -> RunMetrics {
// TODO(Issue #199): alter advance direction for RTL
// TODO(Issue #98): using inter-char and inter-word spacing settings when measuring text
let mut advance = Au(0);
for run.glyphs.iter_glyphs_for_char_range(range) |_i, glyph| {
advance += glyph.advance();
}
let bounds = Rect(Point2D(Au(0), -self.metrics.ascent),
Size2D(advance, self.metrics.ascent + self.metrics.descent));
// TODO(Issue #125): support loose and tight bounding boxes; using the
// ascent+descent and advance is sometimes too generous and
// looking at actual glyph extents can yield a tighter box.
RunMetrics {
advance_width: advance,
bounding_box: bounds,
ascent: self.metrics.ascent,
descent: self.metrics.descent,
}
}
fn shape_text(@mut self, text: &str, store: &mut GlyphStore) {
// TODO(Issue #229): use a more efficient strategy for repetitive shaping.
// For example, Gecko uses a per-"word" hashtable of shaper results.
let shaper = self.get_shaper();
shaper.shape_text(text, store);
}
fn get_descriptor(&self) -> FontDescriptor {
FontDescriptor::new(copy self.style, SelectorPlatformIdentifier(self.handle.face_identifier()))
}
fn glyph_index(&self, codepoint: char) -> Option<GlyphIndex> {
self.handle.glyph_index(codepoint)
}
fn glyph_h_advance(&self, glyph: GlyphIndex) -> FractionalPixel {
match self.handle.glyph_h_advance(glyph) {
Some(adv) => adv,
None => /* FIXME: Need fallback strategy */ 10f as FractionalPixel
}
}
}
/*fn should_destruct_on_fail_without_leaking() {
#[test];
#[should_fail];
let fctx = @FontContext();
let matcher = @FontMatcher(fctx);
let _font = matcher.get_test_font();
fail;
}
fn should_get_glyph_indexes() {
#[test];
let fctx = @FontContext();
let matcher = @FontMatcher(fctx);
let font = matcher.get_test_font();
let glyph_idx = font.glyph_index('w');
assert!(glyph_idx == Some(40u as GlyphIndex));
}
fn should_get_glyph_advance() {
#[test];
#[ignore];
let fctx = @FontContext();
let matcher = @FontMatcher(fctx);
let font = matcher.get_test_font();
let x = font.glyph_h_advance(40u as GlyphIndex);
assert!(x == 15f || x == 16f);
}
// Testing thread safety
fn should_get_glyph_advance_stress() {
#[test];
#[ignore];
let mut ports = ~[];
for iter::repeat(100) {
let (chan, port) = pipes::stream();
ports += [@port];
do task::spawn {
let fctx = @FontContext();
let matcher = @FontMatcher(fctx);
let _font = matcher.get_test_font();
let x = font.glyph_h_advance(40u as GlyphIndex);
assert!(x == 15f || x == 16f);
chan.send(());
}
}
for ports.each |port| {
port.recv();
}
}
fn should_be_able_to_create_instances_in_multiple_threads() {
#[test];
for iter::repeat(10u) {
do task::spawn {
let fctx = @FontContext();
let matcher = @FontMatcher(fctx);
let _font = matcher.get_test_font();
}
}
}
*/
|
{
let cg_font = self.handle.get_CGFont();
let size = self.style.pt_size as AzFloat;
ScaledFont::new(self.backend, &cg_font, size)
}
|
identifier_body
|
init.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/. */
use crate::dom::bindings::codegen::RegisterBindings;
use crate::dom::bindings::proxyhandler;
use crate::script_runtime::JSEngineSetup;
#[cfg(target_os = "linux")]
#[allow(unsafe_code)]
fn perform_platform_specific_initialization() {
// 4096 is default max on many linux systems
const MAX_FILE_LIMIT: libc::rlim_t = 4096;
// Bump up our number of file descriptors to save us from impending doom caused by an onslaught
// of iframes.
unsafe {
let mut rlim = libc::rlimit {
rlim_cur: 0,
rlim_max: 0,
};
match libc::getrlimit(libc::RLIMIT_NOFILE, &mut rlim) {
0 => {
if rlim.rlim_cur >= MAX_FILE_LIMIT {
// we have more than enough
return;
}
rlim.rlim_cur = match rlim.rlim_max {
libc::RLIM_INFINITY => MAX_FILE_LIMIT,
_ => {
if rlim.rlim_max < MAX_FILE_LIMIT {
rlim.rlim_max
} else {
MAX_FILE_LIMIT
}
},
};
match libc::setrlimit(libc::RLIMIT_NOFILE, &rlim) {
0 => (),
_ => warn!("Failed to set file count limit"),
};
},
_ => warn!("Failed to get file count limit"),
};
}
}
#[cfg(not(target_os = "linux"))]
fn
|
() {}
#[allow(unsafe_code)]
pub fn init() -> JSEngineSetup {
unsafe {
proxyhandler::init();
// Create the global vtables used by the (generated) DOM
// bindings to implement JS proxies.
RegisterBindings::RegisterProxyHandlers();
}
perform_platform_specific_initialization();
JSEngineSetup::new()
}
|
perform_platform_specific_initialization
|
identifier_name
|
init.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/. */
use crate::dom::bindings::codegen::RegisterBindings;
use crate::dom::bindings::proxyhandler;
use crate::script_runtime::JSEngineSetup;
#[cfg(target_os = "linux")]
#[allow(unsafe_code)]
fn perform_platform_specific_initialization() {
// 4096 is default max on many linux systems
const MAX_FILE_LIMIT: libc::rlim_t = 4096;
// Bump up our number of file descriptors to save us from impending doom caused by an onslaught
// of iframes.
unsafe {
let mut rlim = libc::rlimit {
rlim_cur: 0,
rlim_max: 0,
};
match libc::getrlimit(libc::RLIMIT_NOFILE, &mut rlim) {
0 => {
if rlim.rlim_cur >= MAX_FILE_LIMIT {
// we have more than enough
return;
}
rlim.rlim_cur = match rlim.rlim_max {
libc::RLIM_INFINITY => MAX_FILE_LIMIT,
_ => {
if rlim.rlim_max < MAX_FILE_LIMIT {
rlim.rlim_max
} else {
MAX_FILE_LIMIT
}
|
},
};
match libc::setrlimit(libc::RLIMIT_NOFILE, &rlim) {
0 => (),
_ => warn!("Failed to set file count limit"),
};
},
_ => warn!("Failed to get file count limit"),
};
}
}
#[cfg(not(target_os = "linux"))]
fn perform_platform_specific_initialization() {}
#[allow(unsafe_code)]
pub fn init() -> JSEngineSetup {
unsafe {
proxyhandler::init();
// Create the global vtables used by the (generated) DOM
// bindings to implement JS proxies.
RegisterBindings::RegisterProxyHandlers();
}
perform_platform_specific_initialization();
JSEngineSetup::new()
}
|
random_line_split
|
|
init.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/. */
use crate::dom::bindings::codegen::RegisterBindings;
use crate::dom::bindings::proxyhandler;
use crate::script_runtime::JSEngineSetup;
#[cfg(target_os = "linux")]
#[allow(unsafe_code)]
fn perform_platform_specific_initialization() {
// 4096 is default max on many linux systems
const MAX_FILE_LIMIT: libc::rlim_t = 4096;
// Bump up our number of file descriptors to save us from impending doom caused by an onslaught
// of iframes.
unsafe {
let mut rlim = libc::rlimit {
rlim_cur: 0,
rlim_max: 0,
};
match libc::getrlimit(libc::RLIMIT_NOFILE, &mut rlim) {
0 => {
if rlim.rlim_cur >= MAX_FILE_LIMIT {
// we have more than enough
return;
}
rlim.rlim_cur = match rlim.rlim_max {
libc::RLIM_INFINITY => MAX_FILE_LIMIT,
_ => {
if rlim.rlim_max < MAX_FILE_LIMIT {
rlim.rlim_max
} else {
MAX_FILE_LIMIT
}
},
};
match libc::setrlimit(libc::RLIMIT_NOFILE, &rlim) {
0 => (),
_ => warn!("Failed to set file count limit"),
};
},
_ => warn!("Failed to get file count limit"),
};
}
}
#[cfg(not(target_os = "linux"))]
fn perform_platform_specific_initialization()
|
#[allow(unsafe_code)]
pub fn init() -> JSEngineSetup {
unsafe {
proxyhandler::init();
// Create the global vtables used by the (generated) DOM
// bindings to implement JS proxies.
RegisterBindings::RegisterProxyHandlers();
}
perform_platform_specific_initialization();
JSEngineSetup::new()
}
|
{}
|
identifier_body
|
init.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/. */
use crate::dom::bindings::codegen::RegisterBindings;
use crate::dom::bindings::proxyhandler;
use crate::script_runtime::JSEngineSetup;
#[cfg(target_os = "linux")]
#[allow(unsafe_code)]
fn perform_platform_specific_initialization() {
// 4096 is default max on many linux systems
const MAX_FILE_LIMIT: libc::rlim_t = 4096;
// Bump up our number of file descriptors to save us from impending doom caused by an onslaught
// of iframes.
unsafe {
let mut rlim = libc::rlimit {
rlim_cur: 0,
rlim_max: 0,
};
match libc::getrlimit(libc::RLIMIT_NOFILE, &mut rlim) {
0 => {
if rlim.rlim_cur >= MAX_FILE_LIMIT {
// we have more than enough
return;
}
rlim.rlim_cur = match rlim.rlim_max {
libc::RLIM_INFINITY => MAX_FILE_LIMIT,
_ =>
|
,
};
match libc::setrlimit(libc::RLIMIT_NOFILE, &rlim) {
0 => (),
_ => warn!("Failed to set file count limit"),
};
},
_ => warn!("Failed to get file count limit"),
};
}
}
#[cfg(not(target_os = "linux"))]
fn perform_platform_specific_initialization() {}
#[allow(unsafe_code)]
pub fn init() -> JSEngineSetup {
unsafe {
proxyhandler::init();
// Create the global vtables used by the (generated) DOM
// bindings to implement JS proxies.
RegisterBindings::RegisterProxyHandlers();
}
perform_platform_specific_initialization();
JSEngineSetup::new()
}
|
{
if rlim.rlim_max < MAX_FILE_LIMIT {
rlim.rlim_max
} else {
MAX_FILE_LIMIT
}
}
|
conditional_block
|
TowersOfHanoi.rs
|
use std::iter::repeat;
struct TowersOfHanoi {
_n: usize,
}
impl TowersOfHanoi {
fn new (n: usize) -> TowersOfHanoi {
TowersOfHanoi {
_n: n,
}
}
fn hanoi(&self, m: &usize, from: usize, to: usize, work: usize, s:&mut Vec<Vec<usize>>)
|
}
}
fn disp(&self, a: Vec<Vec<usize>>) -> String {
// println!("a:{:?}", &a);
if a[0].is_empty() && a[1].is_empty() && a[2].is_empty() {
// println!("disp\n");
// println!("{:?}", a);
return (vec!["-"; &self._n*2*3]).join("") + "\n"
} else {
let str_disp = a.iter()
.map(|x|
Some(x).and_then(
|tmp| if tmp.len()==0 {Some(vec![])}
// skip(k) skips k elements, not k-th element.
else {Some(x.iter().skip(1).map(|e| *e).collect::<Vec<usize>>())}
).unwrap())
.collect::<Vec<Vec<usize>>>();
// println!("str_disp:{:?}", str_disp);
let tail = &self.disp(str_disp);
let head = a.iter()
.map(|x| {
Some(x).and_then(|tmp|
if tmp.len()==0 {Some(0)}
else {Some(*tmp.first().unwrap())}).unwrap()})
.map(|x| {
let s1 = (vec![" "; &self._n-x]).join("");
let s2 = (vec!["■■"; x]).join("");
let s3 = (vec![" "; &self._n-x]).join("");
return s1 + s2.as_str() + s3.as_str() + ""})
.collect::<Vec<String>>();
return tail.clone() + "\n" + (head.join("").as_str())
}
}
fn start(&self){
let mut s: Vec<Vec<usize>> = repeat(vec![]).take(3).collect();
s[0] = (1..&self._n+1).collect();
&self.hanoi(&self._n, 0, 2, 1, &mut s);
}
}
fn main() {
let toh = TowersOfHanoi::new(4);
toh.start();
}
|
{
if m.eq(&1) {
// println!("pre:{:?}", &s[from]);
// don't use swap_remove, because of swap_remove behave strange.
let head: usize = *s[from].first().unwrap();
s[from].remove(0);
// println!("post:{:?}", &s[from]);
s[to].insert(0, head); //v.slice(1, 3);
// println!("post:{:?}", &s);
let disp_vec = s.iter()
.map(|v| {
let mut tmp = v.clone();
tmp.reverse();
tmp})
.collect::<Vec<Vec<usize>>>();
println!("{}", &self.disp(disp_vec.clone()));
} else {
&self.hanoi(&(m-1), from, work, to, s);
&self.hanoi(&1, from, to, work, s);
&self.hanoi(&(m-1), work, to, from, s);
|
identifier_body
|
TowersOfHanoi.rs
|
use std::iter::repeat;
struct TowersOfHanoi {
_n: usize,
}
impl TowersOfHanoi {
fn new (n: usize) -> TowersOfHanoi {
TowersOfHanoi {
_n: n,
}
}
fn hanoi(&self, m: &usize, from: usize, to: usize, work: usize, s:&mut Vec<Vec<usize>>) {
if m.eq(&1) {
// println!("pre:{:?}", &s[from]);
// don't use swap_remove, because of swap_remove behave strange.
let head: usize = *s[from].first().unwrap();
s[from].remove(0);
// println!("post:{:?}", &s[from]);
s[to].insert(0, head); //v.slice(1, 3);
// println!("post:{:?}", &s);
let disp_vec = s.iter()
.map(|v| {
let mut tmp = v.clone();
tmp.reverse();
tmp})
.collect::<Vec<Vec<usize>>>();
println!("{}", &self.disp(disp_vec.clone()));
} else {
&self.hanoi(&(m-1), from, work, to, s);
&self.hanoi(&1, from, to, work, s);
&self.hanoi(&(m-1), work, to, from, s);
}
}
fn disp(&self, a: Vec<Vec<usize>>) -> String {
// println!("a:{:?}", &a);
if a[0].is_empty() && a[1].is_empty() && a[2].is_empty() {
// println!("disp\n");
// println!("{:?}", a);
return (vec!["-"; &self._n*2*3]).join("") + "\n"
} else {
let str_disp = a.iter()
.map(|x|
Some(x).and_then(
|tmp| if tmp.len()==0 {Some(vec![])}
// skip(k) skips k elements, not k-th element.
else {Some(x.iter().skip(1).map(|e| *e).collect::<Vec<usize>>())}
|
// println!("str_disp:{:?}", str_disp);
let tail = &self.disp(str_disp);
let head = a.iter()
.map(|x| {
Some(x).and_then(|tmp|
if tmp.len()==0 {Some(0)}
else {Some(*tmp.first().unwrap())}).unwrap()})
.map(|x| {
let s1 = (vec![" "; &self._n-x]).join("");
let s2 = (vec!["■■"; x]).join("");
let s3 = (vec![" "; &self._n-x]).join("");
return s1 + s2.as_str() + s3.as_str() + ""})
.collect::<Vec<String>>();
return tail.clone() + "\n" + (head.join("").as_str())
}
}
fn start(&self){
let mut s: Vec<Vec<usize>> = repeat(vec![]).take(3).collect();
s[0] = (1..&self._n+1).collect();
&self.hanoi(&self._n, 0, 2, 1, &mut s);
}
}
fn main() {
let toh = TowersOfHanoi::new(4);
toh.start();
}
|
).unwrap())
.collect::<Vec<Vec<usize>>>();
|
random_line_split
|
TowersOfHanoi.rs
|
use std::iter::repeat;
struct TowersOfHanoi {
_n: usize,
}
impl TowersOfHanoi {
fn new (n: usize) -> TowersOfHanoi {
TowersOfHanoi {
_n: n,
}
}
fn hanoi(&self, m: &usize, from: usize, to: usize, work: usize, s:&mut Vec<Vec<usize>>) {
if m.eq(&1) {
// println!("pre:{:?}", &s[from]);
// don't use swap_remove, because of swap_remove behave strange.
let head: usize = *s[from].first().unwrap();
s[from].remove(0);
// println!("post:{:?}", &s[from]);
s[to].insert(0, head); //v.slice(1, 3);
// println!("post:{:?}", &s);
let disp_vec = s.iter()
.map(|v| {
let mut tmp = v.clone();
tmp.reverse();
tmp})
.collect::<Vec<Vec<usize>>>();
println!("{}", &self.disp(disp_vec.clone()));
} else {
&self.hanoi(&(m-1), from, work, to, s);
&self.hanoi(&1, from, to, work, s);
&self.hanoi(&(m-1), work, to, from, s);
}
}
fn disp(&self, a: Vec<Vec<usize>>) -> String {
// println!("a:{:?}", &a);
if a[0].is_empty() && a[1].is_empty() && a[2].is_empty() {
// println!("disp\n");
// println!("{:?}", a);
return (vec!["-"; &self._n*2*3]).join("") + "\n"
} else
|
let s2 = (vec!["■■"; x]).join("");
let s3 = (vec![" "; &self._n-x]).join("");
return s1 + s2.as_str() + s3.as_str() + ""})
.collect::<Vec<String>>();
return tail.clone() + "\n" + (head.join("").as_str())
}
}
fn start(&self){
let mut s: Vec<Vec<usize>> = repeat(vec![]).take(3).collect();
s[0] = (1..&self._n+1).collect();
&self.hanoi(&self._n, 0, 2, 1, &mut s);
}
}
fn main() {
let toh = TowersOfHanoi::new(4);
toh.start();
}
|
{
let str_disp = a.iter()
.map(|x|
Some(x).and_then(
|tmp| if tmp.len()==0 {Some(vec![])}
// skip(k) skips k elements, not k-th element.
else {Some(x.iter().skip(1).map(|e| *e).collect::<Vec<usize>>())}
).unwrap())
.collect::<Vec<Vec<usize>>>();
// println!("str_disp:{:?}", str_disp);
let tail = &self.disp(str_disp);
let head = a.iter()
.map(|x| {
Some(x).and_then(|tmp|
if tmp.len()==0 {Some(0)}
else {Some(*tmp.first().unwrap())}).unwrap()})
.map(|x| {
let s1 = (vec![" "; &self._n-x]).join("");
|
conditional_block
|
TowersOfHanoi.rs
|
use std::iter::repeat;
struct TowersOfHanoi {
_n: usize,
}
impl TowersOfHanoi {
fn new (n: usize) -> TowersOfHanoi {
TowersOfHanoi {
_n: n,
}
}
fn
|
(&self, m: &usize, from: usize, to: usize, work: usize, s:&mut Vec<Vec<usize>>) {
if m.eq(&1) {
// println!("pre:{:?}", &s[from]);
// don't use swap_remove, because of swap_remove behave strange.
let head: usize = *s[from].first().unwrap();
s[from].remove(0);
// println!("post:{:?}", &s[from]);
s[to].insert(0, head); //v.slice(1, 3);
// println!("post:{:?}", &s);
let disp_vec = s.iter()
.map(|v| {
let mut tmp = v.clone();
tmp.reverse();
tmp})
.collect::<Vec<Vec<usize>>>();
println!("{}", &self.disp(disp_vec.clone()));
} else {
&self.hanoi(&(m-1), from, work, to, s);
&self.hanoi(&1, from, to, work, s);
&self.hanoi(&(m-1), work, to, from, s);
}
}
fn disp(&self, a: Vec<Vec<usize>>) -> String {
// println!("a:{:?}", &a);
if a[0].is_empty() && a[1].is_empty() && a[2].is_empty() {
// println!("disp\n");
// println!("{:?}", a);
return (vec!["-"; &self._n*2*3]).join("") + "\n"
} else {
let str_disp = a.iter()
.map(|x|
Some(x).and_then(
|tmp| if tmp.len()==0 {Some(vec![])}
// skip(k) skips k elements, not k-th element.
else {Some(x.iter().skip(1).map(|e| *e).collect::<Vec<usize>>())}
).unwrap())
.collect::<Vec<Vec<usize>>>();
// println!("str_disp:{:?}", str_disp);
let tail = &self.disp(str_disp);
let head = a.iter()
.map(|x| {
Some(x).and_then(|tmp|
if tmp.len()==0 {Some(0)}
else {Some(*tmp.first().unwrap())}).unwrap()})
.map(|x| {
let s1 = (vec![" "; &self._n-x]).join("");
let s2 = (vec!["■■"; x]).join("");
let s3 = (vec![" "; &self._n-x]).join("");
return s1 + s2.as_str() + s3.as_str() + ""})
.collect::<Vec<String>>();
return tail.clone() + "\n" + (head.join("").as_str())
}
}
fn start(&self){
let mut s: Vec<Vec<usize>> = repeat(vec![]).take(3).collect();
s[0] = (1..&self._n+1).collect();
&self.hanoi(&self._n, 0, 2, 1, &mut s);
}
}
fn main() {
let toh = TowersOfHanoi::new(4);
toh.start();
}
|
hanoi
|
identifier_name
|
build.rs
|
use bindgen::RustTarget;
use pkg_config::Error;
use std::env;
use std::io::Write;
use std::path::PathBuf;
fn main()
|
let stderr = String::from_utf8(output.stderr).unwrap();
if stderr.contains::<&str>(
format!(
"{} was not found in the pkg-config search path",
package_name
)
.as_ref(),
) {
let err_msg = format!(
"
Cannot find {} on the pkg-config search path. Consider installing the library for your
system (e.g. through homebrew, apt-get etc.). Alternatively if it is installed, then add
the directory that contains `cfitsio.pc` on your PKG_CONFIG_PATH, e.g.:
PKG_CONFIG_PATH=<blah> cargo build
",
package_name
);
std::io::stderr().write_all(err_msg.as_bytes()).unwrap();
std::process::exit(output.status.code().unwrap());
}
}
Err(e) => panic!("Unhandled error: {:?}", e),
};
}
|
{
let package_name = "cfitsio";
match pkg_config::probe_library(package_name) {
Ok(_) => {
let bindings = bindgen::builder()
.header("wrapper.h")
.block_extern_crate(true)
.opaque_type("fitsfile")
.opaque_type("FITSfile")
.rust_target(RustTarget::Stable_1_0)
.generate()
.expect("Unable to generate bindings");
let out_path = PathBuf::from(env::var("OUT_DIR").unwrap());
bindings
.write_to_file(out_path.join("bindings.rs"))
.expect("Couldn't write bindings");
}
Err(Error::Failure { output, .. }) => {
// Handle the case where the user has not installed cfitsio, and thusly it is not on
// the PKG_CONFIG_PATH
|
identifier_body
|
build.rs
|
use bindgen::RustTarget;
use pkg_config::Error;
use std::env;
use std::io::Write;
use std::path::PathBuf;
fn main() {
let package_name = "cfitsio";
match pkg_config::probe_library(package_name) {
Ok(_) => {
let bindings = bindgen::builder()
.header("wrapper.h")
.block_extern_crate(true)
.opaque_type("fitsfile")
.opaque_type("FITSfile")
.rust_target(RustTarget::Stable_1_0)
.generate()
.expect("Unable to generate bindings");
let out_path = PathBuf::from(env::var("OUT_DIR").unwrap());
bindings
.write_to_file(out_path.join("bindings.rs"))
.expect("Couldn't write bindings");
}
Err(Error::Failure { output,.. }) =>
|
);
std::io::stderr().write_all(err_msg.as_bytes()).unwrap();
std::process::exit(output.status.code().unwrap());
}
}
Err(e) => panic!("Unhandled error: {:?}", e),
};
}
|
{
// Handle the case where the user has not installed cfitsio, and thusly it is not on
// the PKG_CONFIG_PATH
let stderr = String::from_utf8(output.stderr).unwrap();
if stderr.contains::<&str>(
format!(
"{} was not found in the pkg-config search path",
package_name
)
.as_ref(),
) {
let err_msg = format!(
"
Cannot find {} on the pkg-config search path. Consider installing the library for your
system (e.g. through homebrew, apt-get etc.). Alternatively if it is installed, then add
the directory that contains `cfitsio.pc` on your PKG_CONFIG_PATH, e.g.:
PKG_CONFIG_PATH=<blah> cargo build
",
package_name
|
conditional_block
|
build.rs
|
use bindgen::RustTarget;
use pkg_config::Error;
use std::env;
use std::io::Write;
use std::path::PathBuf;
fn
|
() {
let package_name = "cfitsio";
match pkg_config::probe_library(package_name) {
Ok(_) => {
let bindings = bindgen::builder()
.header("wrapper.h")
.block_extern_crate(true)
.opaque_type("fitsfile")
.opaque_type("FITSfile")
.rust_target(RustTarget::Stable_1_0)
.generate()
.expect("Unable to generate bindings");
let out_path = PathBuf::from(env::var("OUT_DIR").unwrap());
bindings
.write_to_file(out_path.join("bindings.rs"))
.expect("Couldn't write bindings");
}
Err(Error::Failure { output,.. }) => {
// Handle the case where the user has not installed cfitsio, and thusly it is not on
// the PKG_CONFIG_PATH
let stderr = String::from_utf8(output.stderr).unwrap();
if stderr.contains::<&str>(
format!(
"{} was not found in the pkg-config search path",
package_name
)
.as_ref(),
) {
let err_msg = format!(
"
Cannot find {} on the pkg-config search path. Consider installing the library for your
system (e.g. through homebrew, apt-get etc.). Alternatively if it is installed, then add
the directory that contains `cfitsio.pc` on your PKG_CONFIG_PATH, e.g.:
PKG_CONFIG_PATH=<blah> cargo build
",
package_name
);
std::io::stderr().write_all(err_msg.as_bytes()).unwrap();
std::process::exit(output.status.code().unwrap());
}
}
Err(e) => panic!("Unhandled error: {:?}", e),
};
}
|
main
|
identifier_name
|
build.rs
|
use bindgen::RustTarget;
|
fn main() {
let package_name = "cfitsio";
match pkg_config::probe_library(package_name) {
Ok(_) => {
let bindings = bindgen::builder()
.header("wrapper.h")
.block_extern_crate(true)
.opaque_type("fitsfile")
.opaque_type("FITSfile")
.rust_target(RustTarget::Stable_1_0)
.generate()
.expect("Unable to generate bindings");
let out_path = PathBuf::from(env::var("OUT_DIR").unwrap());
bindings
.write_to_file(out_path.join("bindings.rs"))
.expect("Couldn't write bindings");
}
Err(Error::Failure { output,.. }) => {
// Handle the case where the user has not installed cfitsio, and thusly it is not on
// the PKG_CONFIG_PATH
let stderr = String::from_utf8(output.stderr).unwrap();
if stderr.contains::<&str>(
format!(
"{} was not found in the pkg-config search path",
package_name
)
.as_ref(),
) {
let err_msg = format!(
"
Cannot find {} on the pkg-config search path. Consider installing the library for your
system (e.g. through homebrew, apt-get etc.). Alternatively if it is installed, then add
the directory that contains `cfitsio.pc` on your PKG_CONFIG_PATH, e.g.:
PKG_CONFIG_PATH=<blah> cargo build
",
package_name
);
std::io::stderr().write_all(err_msg.as_bytes()).unwrap();
std::process::exit(output.status.code().unwrap());
}
}
Err(e) => panic!("Unhandled error: {:?}", e),
};
}
|
use pkg_config::Error;
use std::env;
use std::io::Write;
use std::path::PathBuf;
|
random_line_split
|
corsym.rs
|
// Copyright © 2015, Peter Atashian
// Licensed under the MIT License <LICENSE.md>
//! Common Language Runtime Debugging Symbol Reader/Writer/Binder Interfaces
DEFINE_GUID!(CorSym_LanguageType_C, 0x63a08714, 0xfc37, 0x11d2,
0x90, 0x4c, 0x0, 0xc0, 0x4f, 0xa3, 0x02, 0xa1);
DEFINE_GUID!(CorSym_LanguageType_CPlusPlus, 0x3a12d0b7, 0xc26c, 0x11d0,
0xb4, 0x42, 0x0, 0xa0, 0x24, 0x4a, 0x1d, 0xd2);
DEFINE_GUID!(CorSym_LanguageType_CSharp, 0x3f5162f8, 0x07c6, 0x11d3,
0x90, 0x53, 0x0, 0xc0, 0x4f, 0xa3, 0x02, 0xa1);
DEFINE_GUID!(CorSym_LanguageType_Basic, 0x3a12d0b8, 0xc26c, 0x11d0,
0xb4, 0x42, 0x0, 0xa0, 0x24, 0x4a, 0x1d, 0xd2);
DEFINE_GUID!(CorSym_LanguageType_Java, 0x3a12d0b4, 0xc26c, 0x11d0,
0xb4, 0x42, 0x0, 0xa0, 0x24, 0x4a, 0x1d, 0xd2);
DEFINE_GUID!(CorSym_LanguageType_Cobol, 0xaf046cd1, 0xd0e1, 0x11d2,
0x97, 0x7c, 0x0, 0xa0, 0xc9, 0xb4, 0xd5, 0xc);
DEFINE_GUID!(CorSym_LanguageType_Pascal, 0xaf046cd2, 0xd0e1, 0x11d2,
0x97, 0x7c, 0x0, 0xa0, 0xc9, 0xb4, 0xd5, 0xc);
DEFINE_GUID!(CorSym_LanguageType_ILAssembly, 0xaf046cd3, 0xd0e1, 0x11d2,
0x97, 0x7c, 0x0, 0xa0, 0xc9, 0xb4, 0xd5, 0xc);
DEFINE_GUID!(CorSym_LanguageType_JScript, 0x3a12d0b6, 0xc26c, 0x11d0,
0xb4, 0x42, 0x00, 0xa0, 0x24, 0x4a, 0x1d, 0xd2);
DEFINE_GUID!(CorSym_LanguageType_SMC, 0xd9b9f7b, 0x6611, 0x11d3,
0xbd, 0x2a, 0x0, 0x0, 0xf8, 0x8, 0x49, 0xbd);
DEFINE_GUID!(CorSym_LanguageType_MCPlusPlus, 0x4b35fde8, 0x07c6, 0x11d3,
0x90, 0x53, 0x0, 0xc0, 0x4f, 0xa3, 0x02, 0xa1);
DEFINE_GUID!(CorSym_LanguageVendor_Microsoft, 0x994b45c4, 0xe6e9, 0x11d2,
0x90, 0x3f, 0x00, 0xc0, 0x4f, 0xa3, 0x02, 0xa1);
DEFINE_GUID!(CorSym_DocumentType_Text, 0x5a869d0b, 0x6611, 0x11d3,
0xbd, 0x2a, 0x0, 0x0, 0xf8, 0x8, 0x49, 0xbd);
DEFINE_GUID!(CorSym_DocumentType_MC, 0xeb40cb65, 0x3c1f, 0x4352,
0x9d, 0x7b, 0xba, 0xf, 0xc4, 0x7a, 0x9d, 0x77);
DEFINE_GUID!(CorSym_SourceHash_MD5, 0x406ea660, 0x64cf, 0x4c82,
0xb6, 0xf0, 0x42, 0xd4, 0x81, 0x72, 0xa7, 0x99);
DEFINE_GUID!(CorSym_SourceHash_SHA1, 0xff1816ec, 0xaa5e, 0x4d10,
0x87, 0xf7, 0x6f, 0x49, 0x63, 0x83, 0x34, 0x60);
#[repr(i32)] #[derive(Clone, Copy, Debug)] #[allow(unused_qualifications)]
pub enum CorSymAddrKind {
ADDR_IL_OFFSET = 1,
ADDR_NATIVE_RVA = 2,
ADDR_NATIVE_REGISTER = 3,
ADDR_NATIVE_REGREL = 4,
ADDR_NATIVE_OFFSET = 5,
ADDR_NATIVE_REGREG = 6,
ADDR_NATIVE_REGSTK = 7,
ADDR_NATIVE_STKREG = 8,
ADDR_BITFIELD = 9,
ADDR_NATIVE_ISECTOFFSET = 10,
}
pub use self::CorSymAddrKind::*;
#[repr(i32)] #[derive(Clone, Copy, Debug)] #[allow(unused_qualifications)]
pub enum CorSymVarFlag {
VAR_IS_COMP_GEN = 1,
#[doc(hidden)] __,
}
pub use self::CorSymVarFlag::*;
RIDL!(
interface ISymUnmanagedBinder(ISymUnmanagedBinderVtbl): IUnknown(IUnknownVtbl) {
fn GetReaderForFile(
&mut self, importer: *mut ::IUnknown, fileName: *const ::WCHAR, searchPath: *const ::WCHAR,
pRetVal: *mut *mut ISymUnmanagedReader
) -> ::HRESULT,
fn GetReaderFromStream(
&mut self, importer: *mut ::IUnknown, pstream: *mut ::IStream,
pRetVal: *mut *mut ISymUnmanagedReader
) -> ::HRESULT
}
);
#[repr(i32)] #[derive(Clone, Copy, Debug)] #[allow(unused_qualifications)]
pub enum CorSymSearchPolicyAttributes {
AllowRegistryAccess = 0x1,
AllowSymbolServerAccess = 0x2,
AllowOriginalPathAccess = 0x4,
AllowReferencePathAccess = 0x8,
}
pub use self::CorSymSearchPolicyAttributes::*;
RIDL!(
interface ISymUnmanagedBinder2(ISymUnmanagedBinder2Vtbl):
ISymUnmanagedBinder(ISymUnmanagedBinderVtbl) {
fn GetReaderForFile2(
&mut self, importer: *mut ::IUnknown, fileName: *const ::WCHAR, searchPath: *const ::WCHAR,
searchPolicy: ::ULONG32, pRetVal: *mut *mut ISymUnmanagedReader
) -> ::HRESULT
}
);
#[derive(Clone, Copy)]
pub struct I
|
SymUnmanagedReader;
|
identifier_name
|
|
corsym.rs
|
// Copyright © 2015, Peter Atashian
// Licensed under the MIT License <LICENSE.md>
//! Common Language Runtime Debugging Symbol Reader/Writer/Binder Interfaces
DEFINE_GUID!(CorSym_LanguageType_C, 0x63a08714, 0xfc37, 0x11d2,
0x90, 0x4c, 0x0, 0xc0, 0x4f, 0xa3, 0x02, 0xa1);
DEFINE_GUID!(CorSym_LanguageType_CPlusPlus, 0x3a12d0b7, 0xc26c, 0x11d0,
0xb4, 0x42, 0x0, 0xa0, 0x24, 0x4a, 0x1d, 0xd2);
DEFINE_GUID!(CorSym_LanguageType_CSharp, 0x3f5162f8, 0x07c6, 0x11d3,
0x90, 0x53, 0x0, 0xc0, 0x4f, 0xa3, 0x02, 0xa1);
DEFINE_GUID!(CorSym_LanguageType_Basic, 0x3a12d0b8, 0xc26c, 0x11d0,
0xb4, 0x42, 0x0, 0xa0, 0x24, 0x4a, 0x1d, 0xd2);
DEFINE_GUID!(CorSym_LanguageType_Java, 0x3a12d0b4, 0xc26c, 0x11d0,
0xb4, 0x42, 0x0, 0xa0, 0x24, 0x4a, 0x1d, 0xd2);
DEFINE_GUID!(CorSym_LanguageType_Cobol, 0xaf046cd1, 0xd0e1, 0x11d2,
0x97, 0x7c, 0x0, 0xa0, 0xc9, 0xb4, 0xd5, 0xc);
DEFINE_GUID!(CorSym_LanguageType_Pascal, 0xaf046cd2, 0xd0e1, 0x11d2,
0x97, 0x7c, 0x0, 0xa0, 0xc9, 0xb4, 0xd5, 0xc);
DEFINE_GUID!(CorSym_LanguageType_ILAssembly, 0xaf046cd3, 0xd0e1, 0x11d2,
0x97, 0x7c, 0x0, 0xa0, 0xc9, 0xb4, 0xd5, 0xc);
DEFINE_GUID!(CorSym_LanguageType_JScript, 0x3a12d0b6, 0xc26c, 0x11d0,
0xb4, 0x42, 0x00, 0xa0, 0x24, 0x4a, 0x1d, 0xd2);
DEFINE_GUID!(CorSym_LanguageType_SMC, 0xd9b9f7b, 0x6611, 0x11d3,
0xbd, 0x2a, 0x0, 0x0, 0xf8, 0x8, 0x49, 0xbd);
DEFINE_GUID!(CorSym_LanguageType_MCPlusPlus, 0x4b35fde8, 0x07c6, 0x11d3,
0x90, 0x53, 0x0, 0xc0, 0x4f, 0xa3, 0x02, 0xa1);
DEFINE_GUID!(CorSym_LanguageVendor_Microsoft, 0x994b45c4, 0xe6e9, 0x11d2,
0x90, 0x3f, 0x00, 0xc0, 0x4f, 0xa3, 0x02, 0xa1);
DEFINE_GUID!(CorSym_DocumentType_Text, 0x5a869d0b, 0x6611, 0x11d3,
0xbd, 0x2a, 0x0, 0x0, 0xf8, 0x8, 0x49, 0xbd);
DEFINE_GUID!(CorSym_DocumentType_MC, 0xeb40cb65, 0x3c1f, 0x4352,
0x9d, 0x7b, 0xba, 0xf, 0xc4, 0x7a, 0x9d, 0x77);
DEFINE_GUID!(CorSym_SourceHash_MD5, 0x406ea660, 0x64cf, 0x4c82,
0xb6, 0xf0, 0x42, 0xd4, 0x81, 0x72, 0xa7, 0x99);
DEFINE_GUID!(CorSym_SourceHash_SHA1, 0xff1816ec, 0xaa5e, 0x4d10,
0x87, 0xf7, 0x6f, 0x49, 0x63, 0x83, 0x34, 0x60);
#[repr(i32)] #[derive(Clone, Copy, Debug)] #[allow(unused_qualifications)]
pub enum CorSymAddrKind {
ADDR_IL_OFFSET = 1,
ADDR_NATIVE_RVA = 2,
ADDR_NATIVE_REGISTER = 3,
ADDR_NATIVE_REGREL = 4,
ADDR_NATIVE_OFFSET = 5,
ADDR_NATIVE_REGREG = 6,
ADDR_NATIVE_REGSTK = 7,
ADDR_NATIVE_STKREG = 8,
ADDR_BITFIELD = 9,
ADDR_NATIVE_ISECTOFFSET = 10,
}
pub use self::CorSymAddrKind::*;
#[repr(i32)] #[derive(Clone, Copy, Debug)] #[allow(unused_qualifications)]
pub enum CorSymVarFlag {
VAR_IS_COMP_GEN = 1,
#[doc(hidden)] __,
}
pub use self::CorSymVarFlag::*;
RIDL!(
interface ISymUnmanagedBinder(ISymUnmanagedBinderVtbl): IUnknown(IUnknownVtbl) {
fn GetReaderForFile(
&mut self, importer: *mut ::IUnknown, fileName: *const ::WCHAR, searchPath: *const ::WCHAR,
pRetVal: *mut *mut ISymUnmanagedReader
) -> ::HRESULT,
fn GetReaderFromStream(
&mut self, importer: *mut ::IUnknown, pstream: *mut ::IStream,
pRetVal: *mut *mut ISymUnmanagedReader
) -> ::HRESULT
}
);
#[repr(i32)] #[derive(Clone, Copy, Debug)] #[allow(unused_qualifications)]
pub enum CorSymSearchPolicyAttributes {
AllowRegistryAccess = 0x1,
AllowSymbolServerAccess = 0x2,
AllowOriginalPathAccess = 0x4,
AllowReferencePathAccess = 0x8,
}
pub use self::CorSymSearchPolicyAttributes::*;
RIDL!(
interface ISymUnmanagedBinder2(ISymUnmanagedBinder2Vtbl):
ISymUnmanagedBinder(ISymUnmanagedBinderVtbl) {
fn GetReaderForFile2(
&mut self, importer: *mut ::IUnknown, fileName: *const ::WCHAR, searchPath: *const ::WCHAR,
searchPolicy: ::ULONG32, pRetVal: *mut *mut ISymUnmanagedReader
) -> ::HRESULT
}
|
pub struct ISymUnmanagedReader;
|
);
#[derive(Clone, Copy)]
|
random_line_split
|
home.rs
|
use iron::prelude::*;
use iron::middleware::Handler;
use iron::status;
use iron::headers::{ContentType};
use utils::Utils;
use rustview::view::View;
pub struct Index {
utils: Utils,
template: View,
}
impl Index {
pub fn
|
(utils: Utils, admin_template: View) -> Index {
Index {
utils: utils,
template: admin_template,
}
}
}
impl Handler for Index {
fn handle(&self, req: &mut Request) -> IronResult<Response> {
let model = json!({
"title": "Testing",
"newTitle": "New Cool Title here :)",
"helloUser": "Hi Andrei!",
"testText": "It's working!!!!!",
"user": "Andrei",
"child_user": "Home"
});
let mut response = Response::with((status::Ok, self.template.render("home.html", model)));
response.headers.set(ContentType::html());
Ok(response)
}
}
|
new
|
identifier_name
|
home.rs
|
use iron::prelude::*;
use iron::middleware::Handler;
use iron::status;
use iron::headers::{ContentType};
use utils::Utils;
use rustview::view::View;
pub struct Index {
utils: Utils,
template: View,
}
impl Index {
pub fn new(utils: Utils, admin_template: View) -> Index {
Index {
utils: utils,
template: admin_template,
}
}
|
fn handle(&self, req: &mut Request) -> IronResult<Response> {
let model = json!({
"title": "Testing",
"newTitle": "New Cool Title here :)",
"helloUser": "Hi Andrei!",
"testText": "It's working!!!!!",
"user": "Andrei",
"child_user": "Home"
});
let mut response = Response::with((status::Ok, self.template.render("home.html", model)));
response.headers.set(ContentType::html());
Ok(response)
}
}
|
}
impl Handler for Index {
|
random_line_split
|
home.rs
|
use iron::prelude::*;
use iron::middleware::Handler;
use iron::status;
use iron::headers::{ContentType};
use utils::Utils;
use rustview::view::View;
pub struct Index {
utils: Utils,
template: View,
}
impl Index {
pub fn new(utils: Utils, admin_template: View) -> Index
|
}
impl Handler for Index {
fn handle(&self, req: &mut Request) -> IronResult<Response> {
let model = json!({
"title": "Testing",
"newTitle": "New Cool Title here :)",
"helloUser": "Hi Andrei!",
"testText": "It's working!!!!!",
"user": "Andrei",
"child_user": "Home"
});
let mut response = Response::with((status::Ok, self.template.render("home.html", model)));
response.headers.set(ContentType::html());
Ok(response)
}
}
|
{
Index {
utils: utils,
template: admin_template,
}
}
|
identifier_body
|
mod.rs
|
use std::fmt;
use std::str::FromStr;
use model::Strand;
use util;
#[derive(Clone,Debug)]
pub enum GtfFeature {
StartCodon, StopCodon, Exon, CDS, Intron, Gene, Transcript
}
#[derive(Clone,Debug,PartialEq)]
pub enum GtfAnnotation {
GeneId(String),
TranscriptId(String),
ExonNumber(usize),
Unknown(String,String)
}
#[derive(Clone,Debug)]
pub struct GtfRecord {
seqname: String,
source: Option<String>,
feature: Option<GtfFeature>,
start: u64,
end: u64,
score: Option<f64>,
strand: Option<Strand>,
frame: Option<usize>,
annotations: Vec<GtfAnnotation>
}
impl GtfRecord {
pub fn new<TN: ToString>(template_name: &TN, start: u64, end: u64) -> GtfRecord {
assert!(start > 0);
assert!(end >= start);
GtfRecord {
seqname: template_name.to_string(),
start: start,
end: end,
source: None,
feature: None,
score: None,
strand: None,
frame: None,
annotations: Vec::new()
}
}
pub fn seqname(&self) -> &str {
self.seqname.as_ref()
}
pub fn with_seqname<T: ToString>(mut self, new_seqname: &T) -> Self {
self.seqname = new_seqname.to_string();
self
}
pub fn start(&self) -> u64 {
self.start
}
pub fn with_start(mut self, new_start: u64) -> Self {
assert!(new_start > 0);
self.start = new_start;
self
}
pub fn end(&self) -> u64 {
self.end
}
pub fn with_end(mut self, new_end: u64) -> Self {
assert!(new_end >= self.start);
self.start = new_end;
self
}
pub fn has_source(&self) -> bool {
self.source.is_some()
}
pub fn source(&self) -> Option<String> {
self.source.clone()
}
pub fn with_source<T: ToString>(mut self, new_source: &T) -> Self {
self.source = Some(new_source.to_string());
self
}
pub fn without_source(mut self) -> Self {
self.source = None;
self
}
pub fn has_feature(&self) -> bool {
self.feature.is_some()
}
pub fn feature(&self) -> Option<GtfFeature> {
self.feature.clone()
}
pub fn with_feature(mut self, new_feature: GtfFeature) -> Self {
self.feature = Some(new_feature);
self
}
pub fn without_feature(mut self) -> Self {
self.feature = None;
self
}
pub fn has_score(&self) -> bool {
self.score.is_some()
}
pub fn score(&self) -> Option<f64> {
self.score.clone()
}
pub fn with_score(mut self, new_score: f64) -> Self {
self.score = Some(new_score);
self
}
pub fn without_score(mut self) -> Self {
self.feature = None;
self
}
pub fn has_strand(&self) -> bool {
self.strand.is_some()
}
pub fn strand(&self) -> Option<Strand> {
self.strand.clone()
}
pub fn with_strand(mut self, new_strand: Strand) -> Self {
self.strand = Some(new_strand);
self
}
pub fn without_strand(mut self) -> Self {
self.strand = None;
self
}
pub fn has_frame(&self) -> bool {
self.frame.is_some()
}
pub fn frame(&self) -> Option<usize> {
self.frame.clone()
}
pub fn
|
(mut self, new_frame: usize) -> Self {
self.frame = Some(new_frame);
self
}
pub fn without_frame(mut self) -> Self {
self.frame = None;
self
}
pub fn has_annotations(&self) -> bool {
self.annotations.len() > 0
}
pub fn annotations(&self) -> Vec<GtfAnnotation> {
self.annotations.clone()
}
pub fn with_annotations(mut self, new_annotations: Vec<GtfAnnotation>) -> Self {
self.annotations = new_annotations;
self
}
pub fn without_annotations(mut self) -> Self {
self.annotations.clear();
self
}
pub fn add_annotation(mut self, new_annotation: GtfAnnotation) -> Self {
self.annotations.push(new_annotation);
self
}
pub fn remove_annotation(mut self, annotation_to_remove: GtfAnnotation) -> Self {
let p = self.annotations.iter().position(|item| *item == annotation_to_remove);
if p.is_some() {
self.annotations.remove(p.unwrap());
}
self
}
}
impl FromStr for GtfFeature {
type Err = String;
fn from_str(s: &str) -> Result<GtfFeature, String> {
match s.to_lowercase().as_ref() {
"gene" => Ok(GtfFeature::Gene),
"transcript" => Ok(GtfFeature::Transcript),
"cds" => Ok(GtfFeature::CDS),
"exon" => Ok(GtfFeature::Exon),
"intron" => Ok(GtfFeature::Intron),
"start_codon" => Ok(GtfFeature::StartCodon),
"stop_codon" => Ok(GtfFeature::StopCodon),
_ => Err(format!("No such feature '{}'", s))
}
}
}
impl fmt::Display for GtfFeature {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.clone() {
GtfFeature::Gene => write!(f, "gene"),
GtfFeature::Transcript => write!(f, "transcript"),
GtfFeature::CDS => write!(f, "CDS"),
GtfFeature::Exon => write!(f, "exon"),
GtfFeature::Intron => write!(f, "intron"),
GtfFeature::StartCodon => write!(f, "start_codon"),
GtfFeature::StopCodon => write!(f, "stop_codon")
}
}
}
impl FromStr for GtfAnnotation {
type Err = String;
fn from_str(s: &str) -> Result<GtfAnnotation, String> {
let mut parts = util::split(s,'');
parts[1] = parts[1].chars().filter(|c| *c == '"').collect();
match parts[0].to_lowercase().as_ref() {
"gene_id" => Ok(GtfAnnotation::GeneId(parts[1].to_string())),
"transcript_id" => Ok(GtfAnnotation::TranscriptId(parts[1].to_string())),
"exon_number" => match parts[1].parse::<usize>() {
Ok(n) => Ok(GtfAnnotation::ExonNumber(n)),
Err(e) => Err(format!("Can not parse exon number '{}'", e))
},
_ => Ok(GtfAnnotation::Unknown(parts[0].to_string(), parts[1].to_string()))
}
}
}
impl fmt::Display for GtfAnnotation {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.clone() {
GtfAnnotation::GeneId(s) => write!(f, "gene_id \"{}\"", s),
GtfAnnotation::TranscriptId(s) => write!(f, "transcript_id \"{}\"", s),
GtfAnnotation::ExonNumber(s) => write!(f, "exon_number {}", s),
GtfAnnotation::Unknown(k,v) => write!(f, "{} \"{}\"", k, v)
}
}
}
impl FromStr for GtfRecord {
type Err = String;
fn from_str(s: &str) -> Result<GtfRecord, String> {
let parts = util::split(s, '\t');
if parts.len()!= 9 {
return Err(format!("Expected 9 cells separated by tab but found {}", parts.len()))
}
let mut record = match parts[3].parse::<u64>() {
Err(e) => return Err(format!("Can not parse cell 4 as start position: {}", e)),
Ok(start) => match parts[4].parse::<u64>() {
Err(e) => return Err(format!("Can not parse cell 5 as end position: {}", e)),
Ok(end) => GtfRecord::new(&parts[0], start, end)
}
};
if parts[1]!= "." {
record = record.with_source(&parts[1]);
}
match parts[2].parse::<GtfFeature>() {
Ok(f) => record = record.with_feature(f),
Err(e) => return Err(format!("Can not parse cell 3 (feature): {}", e))
}
if parts[5]!= "." {
match parts[5].parse::<f64>() {
Ok(f) => record = record.with_score(f),
Err(e) => return Err(format!("Can not parse cell 6 (score): {}", e))
}
}
if parts[6]!= "." {
match parts[6].parse::<Strand>() {
Ok(f) => record = record.with_strand(f),
Err(e) => return Err(format!("Can not parse cell 7 (strand): {}", e))
}
}
if parts[7]!= "." {
match parts[7].parse::<usize>() {
Ok(f) => record = record.with_frame(f),
Err(e) => return Err(format!("Can not parse cell 8 (frame): {}", e))
}
}
if parts[8]!= "." {
for annotation in util::split(&parts[8], "; "){
match annotation.parse::<GtfAnnotation>() {
Ok(a) => record = record.add_annotation(a),
Err(e) => return Err(e)
};
}
}
Ok(record)
}
}
impl fmt::Display for GtfRecord {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut cells = Vec::new();
cells.push(self.seqname().to_string());
match self.source() {
Some(s) => cells.push(s),
None => cells.push(".".to_string())
};
match self.feature() {
Some(s) => cells.push(s.to_string()),
None => cells.push(".".to_string())
}
cells.push(format!("{}", self.start()));
cells.push(format!("{}", self.end()));
match self.score() {
Some(s) => cells.push(format!("{}", s)),
None => cells.push(".".to_string())
}
match self.strand() {
Some(s) => match s {
Strand::Forward => cells.push("+".to_string()),
Strand::Backward => cells.push("-".to_string())
},
None => cells.push(".".to_string())
}
match self.frame() {
Some(s) => cells.push(format!("{}", s)),
None => cells.push(".".to_string())
}
let annots = util::join(self.annotations().iter().map(|x| x.to_string()).collect(), "; ");
cells.push(annots);
write!(f, "{}", util::join(cells, "\t"))
}
}
#[cfg(test)]
mod tests {
use io::gtf::GtfRecord;
use std::str::FromStr;
#[test]
fn test_from_and_to_string(){
let orig = "chr1\tprocessed_transcript\ttranscript\t11869\t14409\t.\t+\t.\tgene_id \"ENSG00000223972\"; transcript_id \"ENST00000456328\"; gene_name \"DDX11L1\"; gene_source \"havana\"; gene_biotype \"transcribed_unprocessed_pseudogene\"; transcript_name \"DDX11L1-002\"; transcript_source \"havana\"";
let record = match GtfRecord::from_str(orig) {
Ok(r) => {
assert_eq!(r.seqname(), "chr1".to_string());
assert_eq!(r.start(), 11869u64);
assert_eq!(r.end(), 14409u64);
},
Err(e) => assert!(false, e)
};
}
}
|
with_frame
|
identifier_name
|
mod.rs
|
use std::fmt;
use std::str::FromStr;
use model::Strand;
use util;
#[derive(Clone,Debug)]
pub enum GtfFeature {
StartCodon, StopCodon, Exon, CDS, Intron, Gene, Transcript
}
#[derive(Clone,Debug,PartialEq)]
pub enum GtfAnnotation {
GeneId(String),
TranscriptId(String),
ExonNumber(usize),
Unknown(String,String)
}
#[derive(Clone,Debug)]
pub struct GtfRecord {
seqname: String,
source: Option<String>,
feature: Option<GtfFeature>,
start: u64,
end: u64,
score: Option<f64>,
strand: Option<Strand>,
frame: Option<usize>,
annotations: Vec<GtfAnnotation>
}
impl GtfRecord {
pub fn new<TN: ToString>(template_name: &TN, start: u64, end: u64) -> GtfRecord {
assert!(start > 0);
assert!(end >= start);
GtfRecord {
seqname: template_name.to_string(),
start: start,
end: end,
source: None,
feature: None,
score: None,
strand: None,
frame: None,
annotations: Vec::new()
}
}
pub fn seqname(&self) -> &str {
self.seqname.as_ref()
}
pub fn with_seqname<T: ToString>(mut self, new_seqname: &T) -> Self {
self.seqname = new_seqname.to_string();
self
}
pub fn start(&self) -> u64 {
self.start
}
pub fn with_start(mut self, new_start: u64) -> Self {
assert!(new_start > 0);
self.start = new_start;
self
}
pub fn end(&self) -> u64 {
self.end
}
pub fn with_end(mut self, new_end: u64) -> Self {
assert!(new_end >= self.start);
self.start = new_end;
self
}
pub fn has_source(&self) -> bool {
self.source.is_some()
}
pub fn source(&self) -> Option<String> {
self.source.clone()
}
pub fn with_source<T: ToString>(mut self, new_source: &T) -> Self
|
pub fn without_source(mut self) -> Self {
self.source = None;
self
}
pub fn has_feature(&self) -> bool {
self.feature.is_some()
}
pub fn feature(&self) -> Option<GtfFeature> {
self.feature.clone()
}
pub fn with_feature(mut self, new_feature: GtfFeature) -> Self {
self.feature = Some(new_feature);
self
}
pub fn without_feature(mut self) -> Self {
self.feature = None;
self
}
pub fn has_score(&self) -> bool {
self.score.is_some()
}
pub fn score(&self) -> Option<f64> {
self.score.clone()
}
pub fn with_score(mut self, new_score: f64) -> Self {
self.score = Some(new_score);
self
}
pub fn without_score(mut self) -> Self {
self.feature = None;
self
}
pub fn has_strand(&self) -> bool {
self.strand.is_some()
}
pub fn strand(&self) -> Option<Strand> {
self.strand.clone()
}
pub fn with_strand(mut self, new_strand: Strand) -> Self {
self.strand = Some(new_strand);
self
}
pub fn without_strand(mut self) -> Self {
self.strand = None;
self
}
pub fn has_frame(&self) -> bool {
self.frame.is_some()
}
pub fn frame(&self) -> Option<usize> {
self.frame.clone()
}
pub fn with_frame(mut self, new_frame: usize) -> Self {
self.frame = Some(new_frame);
self
}
pub fn without_frame(mut self) -> Self {
self.frame = None;
self
}
pub fn has_annotations(&self) -> bool {
self.annotations.len() > 0
}
pub fn annotations(&self) -> Vec<GtfAnnotation> {
self.annotations.clone()
}
pub fn with_annotations(mut self, new_annotations: Vec<GtfAnnotation>) -> Self {
self.annotations = new_annotations;
self
}
pub fn without_annotations(mut self) -> Self {
self.annotations.clear();
self
}
pub fn add_annotation(mut self, new_annotation: GtfAnnotation) -> Self {
self.annotations.push(new_annotation);
self
}
pub fn remove_annotation(mut self, annotation_to_remove: GtfAnnotation) -> Self {
let p = self.annotations.iter().position(|item| *item == annotation_to_remove);
if p.is_some() {
self.annotations.remove(p.unwrap());
}
self
}
}
impl FromStr for GtfFeature {
type Err = String;
fn from_str(s: &str) -> Result<GtfFeature, String> {
match s.to_lowercase().as_ref() {
"gene" => Ok(GtfFeature::Gene),
"transcript" => Ok(GtfFeature::Transcript),
"cds" => Ok(GtfFeature::CDS),
"exon" => Ok(GtfFeature::Exon),
"intron" => Ok(GtfFeature::Intron),
"start_codon" => Ok(GtfFeature::StartCodon),
"stop_codon" => Ok(GtfFeature::StopCodon),
_ => Err(format!("No such feature '{}'", s))
}
}
}
impl fmt::Display for GtfFeature {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.clone() {
GtfFeature::Gene => write!(f, "gene"),
GtfFeature::Transcript => write!(f, "transcript"),
GtfFeature::CDS => write!(f, "CDS"),
GtfFeature::Exon => write!(f, "exon"),
GtfFeature::Intron => write!(f, "intron"),
GtfFeature::StartCodon => write!(f, "start_codon"),
GtfFeature::StopCodon => write!(f, "stop_codon")
}
}
}
impl FromStr for GtfAnnotation {
type Err = String;
fn from_str(s: &str) -> Result<GtfAnnotation, String> {
let mut parts = util::split(s,'');
parts[1] = parts[1].chars().filter(|c| *c == '"').collect();
match parts[0].to_lowercase().as_ref() {
"gene_id" => Ok(GtfAnnotation::GeneId(parts[1].to_string())),
"transcript_id" => Ok(GtfAnnotation::TranscriptId(parts[1].to_string())),
"exon_number" => match parts[1].parse::<usize>() {
Ok(n) => Ok(GtfAnnotation::ExonNumber(n)),
Err(e) => Err(format!("Can not parse exon number '{}'", e))
},
_ => Ok(GtfAnnotation::Unknown(parts[0].to_string(), parts[1].to_string()))
}
}
}
impl fmt::Display for GtfAnnotation {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.clone() {
GtfAnnotation::GeneId(s) => write!(f, "gene_id \"{}\"", s),
GtfAnnotation::TranscriptId(s) => write!(f, "transcript_id \"{}\"", s),
GtfAnnotation::ExonNumber(s) => write!(f, "exon_number {}", s),
GtfAnnotation::Unknown(k,v) => write!(f, "{} \"{}\"", k, v)
}
}
}
impl FromStr for GtfRecord {
type Err = String;
fn from_str(s: &str) -> Result<GtfRecord, String> {
let parts = util::split(s, '\t');
if parts.len()!= 9 {
return Err(format!("Expected 9 cells separated by tab but found {}", parts.len()))
}
let mut record = match parts[3].parse::<u64>() {
Err(e) => return Err(format!("Can not parse cell 4 as start position: {}", e)),
Ok(start) => match parts[4].parse::<u64>() {
Err(e) => return Err(format!("Can not parse cell 5 as end position: {}", e)),
Ok(end) => GtfRecord::new(&parts[0], start, end)
}
};
if parts[1]!= "." {
record = record.with_source(&parts[1]);
}
match parts[2].parse::<GtfFeature>() {
Ok(f) => record = record.with_feature(f),
Err(e) => return Err(format!("Can not parse cell 3 (feature): {}", e))
}
if parts[5]!= "." {
match parts[5].parse::<f64>() {
Ok(f) => record = record.with_score(f),
Err(e) => return Err(format!("Can not parse cell 6 (score): {}", e))
}
}
if parts[6]!= "." {
match parts[6].parse::<Strand>() {
Ok(f) => record = record.with_strand(f),
Err(e) => return Err(format!("Can not parse cell 7 (strand): {}", e))
}
}
if parts[7]!= "." {
match parts[7].parse::<usize>() {
Ok(f) => record = record.with_frame(f),
Err(e) => return Err(format!("Can not parse cell 8 (frame): {}", e))
}
}
if parts[8]!= "." {
for annotation in util::split(&parts[8], "; "){
match annotation.parse::<GtfAnnotation>() {
Ok(a) => record = record.add_annotation(a),
Err(e) => return Err(e)
};
}
}
Ok(record)
}
}
impl fmt::Display for GtfRecord {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut cells = Vec::new();
cells.push(self.seqname().to_string());
match self.source() {
Some(s) => cells.push(s),
None => cells.push(".".to_string())
};
match self.feature() {
Some(s) => cells.push(s.to_string()),
None => cells.push(".".to_string())
}
cells.push(format!("{}", self.start()));
cells.push(format!("{}", self.end()));
match self.score() {
Some(s) => cells.push(format!("{}", s)),
None => cells.push(".".to_string())
}
match self.strand() {
Some(s) => match s {
Strand::Forward => cells.push("+".to_string()),
Strand::Backward => cells.push("-".to_string())
},
None => cells.push(".".to_string())
}
match self.frame() {
Some(s) => cells.push(format!("{}", s)),
None => cells.push(".".to_string())
}
let annots = util::join(self.annotations().iter().map(|x| x.to_string()).collect(), "; ");
cells.push(annots);
write!(f, "{}", util::join(cells, "\t"))
}
}
#[cfg(test)]
mod tests {
use io::gtf::GtfRecord;
use std::str::FromStr;
#[test]
fn test_from_and_to_string(){
let orig = "chr1\tprocessed_transcript\ttranscript\t11869\t14409\t.\t+\t.\tgene_id \"ENSG00000223972\"; transcript_id \"ENST00000456328\"; gene_name \"DDX11L1\"; gene_source \"havana\"; gene_biotype \"transcribed_unprocessed_pseudogene\"; transcript_name \"DDX11L1-002\"; transcript_source \"havana\"";
let record = match GtfRecord::from_str(orig) {
Ok(r) => {
assert_eq!(r.seqname(), "chr1".to_string());
assert_eq!(r.start(), 11869u64);
assert_eq!(r.end(), 14409u64);
},
Err(e) => assert!(false, e)
};
}
}
|
{
self.source = Some(new_source.to_string());
self
}
|
identifier_body
|
mod.rs
|
use std::fmt;
use std::str::FromStr;
use model::Strand;
use util;
#[derive(Clone,Debug)]
pub enum GtfFeature {
StartCodon, StopCodon, Exon, CDS, Intron, Gene, Transcript
}
#[derive(Clone,Debug,PartialEq)]
pub enum GtfAnnotation {
GeneId(String),
TranscriptId(String),
ExonNumber(usize),
Unknown(String,String)
}
#[derive(Clone,Debug)]
pub struct GtfRecord {
seqname: String,
source: Option<String>,
feature: Option<GtfFeature>,
start: u64,
end: u64,
score: Option<f64>,
strand: Option<Strand>,
frame: Option<usize>,
annotations: Vec<GtfAnnotation>
}
impl GtfRecord {
pub fn new<TN: ToString>(template_name: &TN, start: u64, end: u64) -> GtfRecord {
assert!(start > 0);
assert!(end >= start);
GtfRecord {
seqname: template_name.to_string(),
start: start,
end: end,
source: None,
feature: None,
score: None,
strand: None,
frame: None,
annotations: Vec::new()
}
}
pub fn seqname(&self) -> &str {
self.seqname.as_ref()
}
pub fn with_seqname<T: ToString>(mut self, new_seqname: &T) -> Self {
self.seqname = new_seqname.to_string();
self
}
pub fn start(&self) -> u64 {
self.start
}
pub fn with_start(mut self, new_start: u64) -> Self {
assert!(new_start > 0);
self.start = new_start;
self
}
pub fn end(&self) -> u64 {
self.end
}
pub fn with_end(mut self, new_end: u64) -> Self {
assert!(new_end >= self.start);
self.start = new_end;
self
}
pub fn has_source(&self) -> bool {
self.source.is_some()
}
pub fn source(&self) -> Option<String> {
self.source.clone()
}
pub fn with_source<T: ToString>(mut self, new_source: &T) -> Self {
self.source = Some(new_source.to_string());
self
}
pub fn without_source(mut self) -> Self {
self.source = None;
self
}
pub fn has_feature(&self) -> bool {
self.feature.is_some()
}
pub fn feature(&self) -> Option<GtfFeature> {
self.feature.clone()
}
pub fn with_feature(mut self, new_feature: GtfFeature) -> Self {
self.feature = Some(new_feature);
self
}
pub fn without_feature(mut self) -> Self {
self.feature = None;
self
}
pub fn has_score(&self) -> bool {
self.score.is_some()
}
pub fn score(&self) -> Option<f64> {
self.score.clone()
}
pub fn with_score(mut self, new_score: f64) -> Self {
self.score = Some(new_score);
self
}
pub fn without_score(mut self) -> Self {
self.feature = None;
self
}
pub fn has_strand(&self) -> bool {
self.strand.is_some()
}
pub fn strand(&self) -> Option<Strand> {
self.strand.clone()
}
pub fn with_strand(mut self, new_strand: Strand) -> Self {
self.strand = Some(new_strand);
self
}
pub fn without_strand(mut self) -> Self {
self.strand = None;
self
}
pub fn has_frame(&self) -> bool {
self.frame.is_some()
}
pub fn frame(&self) -> Option<usize> {
self.frame.clone()
}
pub fn with_frame(mut self, new_frame: usize) -> Self {
self.frame = Some(new_frame);
self
}
pub fn without_frame(mut self) -> Self {
self.frame = None;
self
}
pub fn has_annotations(&self) -> bool {
self.annotations.len() > 0
}
pub fn annotations(&self) -> Vec<GtfAnnotation> {
self.annotations.clone()
}
pub fn with_annotations(mut self, new_annotations: Vec<GtfAnnotation>) -> Self {
self.annotations = new_annotations;
self
}
pub fn without_annotations(mut self) -> Self {
self.annotations.clear();
self
}
pub fn add_annotation(mut self, new_annotation: GtfAnnotation) -> Self {
self.annotations.push(new_annotation);
self
}
pub fn remove_annotation(mut self, annotation_to_remove: GtfAnnotation) -> Self {
let p = self.annotations.iter().position(|item| *item == annotation_to_remove);
if p.is_some() {
self.annotations.remove(p.unwrap());
}
self
}
}
impl FromStr for GtfFeature {
type Err = String;
fn from_str(s: &str) -> Result<GtfFeature, String> {
match s.to_lowercase().as_ref() {
"gene" => Ok(GtfFeature::Gene),
"transcript" => Ok(GtfFeature::Transcript),
"cds" => Ok(GtfFeature::CDS),
"exon" => Ok(GtfFeature::Exon),
"intron" => Ok(GtfFeature::Intron),
"start_codon" => Ok(GtfFeature::StartCodon),
"stop_codon" => Ok(GtfFeature::StopCodon),
_ => Err(format!("No such feature '{}'", s))
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.clone() {
GtfFeature::Gene => write!(f, "gene"),
GtfFeature::Transcript => write!(f, "transcript"),
GtfFeature::CDS => write!(f, "CDS"),
GtfFeature::Exon => write!(f, "exon"),
GtfFeature::Intron => write!(f, "intron"),
GtfFeature::StartCodon => write!(f, "start_codon"),
GtfFeature::StopCodon => write!(f, "stop_codon")
}
}
}
impl FromStr for GtfAnnotation {
type Err = String;
fn from_str(s: &str) -> Result<GtfAnnotation, String> {
let mut parts = util::split(s,'');
parts[1] = parts[1].chars().filter(|c| *c == '"').collect();
match parts[0].to_lowercase().as_ref() {
"gene_id" => Ok(GtfAnnotation::GeneId(parts[1].to_string())),
"transcript_id" => Ok(GtfAnnotation::TranscriptId(parts[1].to_string())),
"exon_number" => match parts[1].parse::<usize>() {
Ok(n) => Ok(GtfAnnotation::ExonNumber(n)),
Err(e) => Err(format!("Can not parse exon number '{}'", e))
},
_ => Ok(GtfAnnotation::Unknown(parts[0].to_string(), parts[1].to_string()))
}
}
}
impl fmt::Display for GtfAnnotation {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.clone() {
GtfAnnotation::GeneId(s) => write!(f, "gene_id \"{}\"", s),
GtfAnnotation::TranscriptId(s) => write!(f, "transcript_id \"{}\"", s),
GtfAnnotation::ExonNumber(s) => write!(f, "exon_number {}", s),
GtfAnnotation::Unknown(k,v) => write!(f, "{} \"{}\"", k, v)
}
}
}
impl FromStr for GtfRecord {
type Err = String;
fn from_str(s: &str) -> Result<GtfRecord, String> {
let parts = util::split(s, '\t');
if parts.len()!= 9 {
return Err(format!("Expected 9 cells separated by tab but found {}", parts.len()))
}
let mut record = match parts[3].parse::<u64>() {
Err(e) => return Err(format!("Can not parse cell 4 as start position: {}", e)),
Ok(start) => match parts[4].parse::<u64>() {
Err(e) => return Err(format!("Can not parse cell 5 as end position: {}", e)),
Ok(end) => GtfRecord::new(&parts[0], start, end)
}
};
if parts[1]!= "." {
record = record.with_source(&parts[1]);
}
match parts[2].parse::<GtfFeature>() {
Ok(f) => record = record.with_feature(f),
Err(e) => return Err(format!("Can not parse cell 3 (feature): {}", e))
}
if parts[5]!= "." {
match parts[5].parse::<f64>() {
Ok(f) => record = record.with_score(f),
Err(e) => return Err(format!("Can not parse cell 6 (score): {}", e))
}
}
if parts[6]!= "." {
match parts[6].parse::<Strand>() {
Ok(f) => record = record.with_strand(f),
Err(e) => return Err(format!("Can not parse cell 7 (strand): {}", e))
}
}
if parts[7]!= "." {
match parts[7].parse::<usize>() {
Ok(f) => record = record.with_frame(f),
Err(e) => return Err(format!("Can not parse cell 8 (frame): {}", e))
}
}
if parts[8]!= "." {
for annotation in util::split(&parts[8], "; "){
match annotation.parse::<GtfAnnotation>() {
Ok(a) => record = record.add_annotation(a),
Err(e) => return Err(e)
};
}
}
Ok(record)
}
}
impl fmt::Display for GtfRecord {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut cells = Vec::new();
cells.push(self.seqname().to_string());
match self.source() {
Some(s) => cells.push(s),
None => cells.push(".".to_string())
};
match self.feature() {
Some(s) => cells.push(s.to_string()),
None => cells.push(".".to_string())
}
cells.push(format!("{}", self.start()));
cells.push(format!("{}", self.end()));
match self.score() {
Some(s) => cells.push(format!("{}", s)),
None => cells.push(".".to_string())
}
match self.strand() {
Some(s) => match s {
Strand::Forward => cells.push("+".to_string()),
Strand::Backward => cells.push("-".to_string())
},
None => cells.push(".".to_string())
}
match self.frame() {
Some(s) => cells.push(format!("{}", s)),
None => cells.push(".".to_string())
}
let annots = util::join(self.annotations().iter().map(|x| x.to_string()).collect(), "; ");
cells.push(annots);
write!(f, "{}", util::join(cells, "\t"))
}
}
#[cfg(test)]
mod tests {
use io::gtf::GtfRecord;
use std::str::FromStr;
#[test]
fn test_from_and_to_string(){
let orig = "chr1\tprocessed_transcript\ttranscript\t11869\t14409\t.\t+\t.\tgene_id \"ENSG00000223972\"; transcript_id \"ENST00000456328\"; gene_name \"DDX11L1\"; gene_source \"havana\"; gene_biotype \"transcribed_unprocessed_pseudogene\"; transcript_name \"DDX11L1-002\"; transcript_source \"havana\"";
let record = match GtfRecord::from_str(orig) {
Ok(r) => {
assert_eq!(r.seqname(), "chr1".to_string());
assert_eq!(r.start(), 11869u64);
assert_eq!(r.end(), 14409u64);
},
Err(e) => assert!(false, e)
};
}
}
|
}
}
}
impl fmt::Display for GtfFeature {
|
random_line_split
|
concat_idents.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 ast;
use codemap::span;
use ext::base::*;
use ext::base;
use parse::token;
pub fn expand_syntax_ext(cx: @ext_ctxt, sp: span, tts: &[ast::token_tree])
-> base::MacResult {
let mut res_str = ~"";
for tts.eachi |i, e| {
if i & 1 == 1
|
else {
match *e {
ast::tt_tok(_, token::IDENT(ident,_)) =>
res_str += cx.str_of(ident),
_ => cx.span_fatal(sp, ~"concat_idents! \
requires ident args.")
}
}
}
let res = cx.parse_sess().interner.intern(res_str);
let e = @ast::expr {
id: cx.next_id(),
callee_id: cx.next_id(),
node: ast::expr_path(
@ast::Path {
span: sp,
global: false,
idents: ~[res],
rp: None,
types: ~[],
}
),
span: sp,
};
MRExpr(e)
}
|
{
match *e {
ast::tt_tok(_, token::COMMA) => (),
_ => cx.span_fatal(sp, ~"concat_idents! \
expecting comma.")
}
}
|
conditional_block
|
concat_idents.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 ast;
use codemap::span;
use ext::base::*;
use ext::base;
use parse::token;
pub fn expand_syntax_ext(cx: @ext_ctxt, sp: span, tts: &[ast::token_tree])
-> base::MacResult
|
let e = @ast::expr {
id: cx.next_id(),
callee_id: cx.next_id(),
node: ast::expr_path(
@ast::Path {
span: sp,
global: false,
idents: ~[res],
rp: None,
types: ~[],
}
),
span: sp,
};
MRExpr(e)
}
|
{
let mut res_str = ~"";
for tts.eachi |i, e| {
if i & 1 == 1 {
match *e {
ast::tt_tok(_, token::COMMA) => (),
_ => cx.span_fatal(sp, ~"concat_idents! \
expecting comma.")
}
} else {
match *e {
ast::tt_tok(_, token::IDENT(ident,_)) =>
res_str += cx.str_of(ident),
_ => cx.span_fatal(sp, ~"concat_idents! \
requires ident args.")
}
}
}
let res = cx.parse_sess().interner.intern(res_str);
|
identifier_body
|
concat_idents.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 ast;
use codemap::span;
use ext::base::*;
use ext::base;
use parse::token;
pub fn expand_syntax_ext(cx: @ext_ctxt, sp: span, tts: &[ast::token_tree])
-> base::MacResult {
let mut res_str = ~"";
for tts.eachi |i, e| {
if i & 1 == 1 {
match *e {
ast::tt_tok(_, token::COMMA) => (),
_ => cx.span_fatal(sp, ~"concat_idents! \
expecting comma.")
}
} else {
match *e {
ast::tt_tok(_, token::IDENT(ident,_)) =>
res_str += cx.str_of(ident),
_ => cx.span_fatal(sp, ~"concat_idents! \
requires ident args.")
}
}
}
let res = cx.parse_sess().interner.intern(res_str);
let e = @ast::expr {
|
span: sp,
global: false,
idents: ~[res],
rp: None,
types: ~[],
}
),
span: sp,
};
MRExpr(e)
}
|
id: cx.next_id(),
callee_id: cx.next_id(),
node: ast::expr_path(
@ast::Path {
|
random_line_split
|
concat_idents.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 ast;
use codemap::span;
use ext::base::*;
use ext::base;
use parse::token;
pub fn
|
(cx: @ext_ctxt, sp: span, tts: &[ast::token_tree])
-> base::MacResult {
let mut res_str = ~"";
for tts.eachi |i, e| {
if i & 1 == 1 {
match *e {
ast::tt_tok(_, token::COMMA) => (),
_ => cx.span_fatal(sp, ~"concat_idents! \
expecting comma.")
}
} else {
match *e {
ast::tt_tok(_, token::IDENT(ident,_)) =>
res_str += cx.str_of(ident),
_ => cx.span_fatal(sp, ~"concat_idents! \
requires ident args.")
}
}
}
let res = cx.parse_sess().interner.intern(res_str);
let e = @ast::expr {
id: cx.next_id(),
callee_id: cx.next_id(),
node: ast::expr_path(
@ast::Path {
span: sp,
global: false,
idents: ~[res],
rp: None,
types: ~[],
}
),
span: sp,
};
MRExpr(e)
}
|
expand_syntax_ext
|
identifier_name
|
error.rs
|
use pyo3::{exceptions, PyErr};
use std::error::Error;
pub type BoxError = std::boxed::Box<dyn std::error:: Error + std::marker::Send + std::marker::Sync>;
macro_rules! estructurar {
($nombre: ident, $excepcion: path, $mensaje: expr) => {
pub struct $nombre {
pub source: Option<BoxError>
}
impl std::fmt::Display for $nombre {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, $mensaje)?;
if let Some(error) = &self.source {
write!(f, "\nOrigen: {}", error)?;
|
impl std::fmt::Debug for $nombre {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result{
<$nombre as std::fmt::Display>::fmt(self, f)
}
}
impl std::convert::From<$nombre> for PyErr {
fn from(error: $nombre) -> PyErr {
<$excepcion>::py_err(error.to_string())
}
}
impl Error for $nombre {
fn source(&self) -> Option<&(dyn Error +'static)> {
match &self.source {
Some(error) => Some(error.as_ref()),
None => None
}
}
}
}
}
estructurar!(ErrorSFTP, exceptions::IOError, "Error en sistema de archivos remoto");
estructurar!(ErrorConexion, exceptions::ConnectionError, "Error en conexion ");
estructurar!(ErrorEjecucion, exceptions::SystemError, "Error en ejecución remota");
|
}
Ok(())
}
}
|
random_line_split
|
win_impl.rs
|
use winapi;
use self::winapi::shared::windef::POINT;
use self::winapi::ctypes::c_int;
use self::winapi::um::winuser::*;
use crate::win::keycodes::*;
use crate::{Key, KeyboardControllable, MouseButton, MouseControllable};
use std::mem::*;
/// The main struct for handling the event emitting
#[derive(Default)]
pub struct Enigo;
fn mouse_event(flags: u32, data: u32, dx: i32, dy: i32) {
let mut input = INPUT {
type_: INPUT_MOUSE,
u: unsafe {
transmute(MOUSEINPUT {
dx,
dy,
mouseData: data,
dwFlags: flags,
time: 0,
dwExtraInfo: 0,
})
},
};
unsafe { SendInput(1, &mut input as LPINPUT, size_of::<INPUT>() as c_int) };
}
fn keybd_event(flags: u32, vk: u16, scan: u16) {
let mut input = INPUT {
type_: INPUT_KEYBOARD,
u: unsafe {
transmute_copy(&KEYBDINPUT {
wVk: vk,
wScan: scan,
dwFlags: flags,
time: 0,
dwExtraInfo: 0,
})
},
};
unsafe { SendInput(1, &mut input as LPINPUT, size_of::<INPUT>() as c_int) };
}
impl MouseControllable for Enigo {
fn mouse_move_to(&mut self, x: i32, y: i32) {
mouse_event(
MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_VIRTUALDESK,
0,
(x - unsafe { GetSystemMetrics(SM_XVIRTUALSCREEN) }) * 65535 / unsafe { GetSystemMetrics(SM_CXVIRTUALSCREEN) },
(y - unsafe { GetSystemMetrics(SM_YVIRTUALSCREEN) }) * 65535 / unsafe { GetSystemMetrics(SM_CYVIRTUALSCREEN) },
);
}
fn mouse_move_relative(&mut self, x: i32, y: i32) {
mouse_event(MOUSEEVENTF_MOVE, 0, x, y);
}
fn mouse_down(&mut self, button: MouseButton) {
mouse_event(
match button {
MouseButton::Left => MOUSEEVENTF_LEFTDOWN,
MouseButton::Middle => MOUSEEVENTF_MIDDLEDOWN,
MouseButton::Right => MOUSEEVENTF_RIGHTDOWN,
_ => unimplemented!(),
},
0,
0,
0,
);
}
fn mouse_up(&mut self, button: MouseButton) {
mouse_event(
match button {
MouseButton::Left => MOUSEEVENTF_LEFTUP,
MouseButton::Middle => MOUSEEVENTF_MIDDLEUP,
MouseButton::Right => MOUSEEVENTF_RIGHTUP,
_ => unimplemented!(),
},
0,
0,
0,
);
}
fn mouse_click(&mut self, button: MouseButton) {
self.mouse_down(button);
self.mouse_up(button);
}
fn mouse_scroll_x(&mut self, length: i32) {
mouse_event(MOUSEEVENTF_HWHEEL, unsafe { transmute(length * 120) }, 0, 0);
}
fn mouse_scroll_y(&mut self, length: i32) {
mouse_event(MOUSEEVENTF_WHEEL, unsafe { transmute(length * 120) }, 0, 0);
}
}
impl KeyboardControllable for Enigo {
fn key_sequence(&mut self, sequence: &str) {
let mut buffer = [0; 2];
for c in sequence.chars() {
// Windows uses uft-16 encoding. We need to check
// for variable length characters. As such some
// characters can be 32 bit long and those are
// encoded in such called hight and low surrogates
// each 16 bit wide that needs to be send after
// another to the SendInput function without
// being interrupted by "keyup"
let result = c.encode_utf16(&mut buffer);
if result.len() == 1 {
self.unicode_key_click(result[0]);
} else {
for utf16_surrogate in result {
self.unicode_key_down(utf16_surrogate.clone());
}
// do i need to produce a keyup?
// self.unicode_key_up(0);
}
}
}
fn
|
(&mut self, key: Key) {
let scancode = self.key_to_scancode(key);
use std::{thread, time};
keybd_event(KEYEVENTF_SCANCODE, 0, scancode);
thread::sleep(time::Duration::from_millis(20));
keybd_event(KEYEVENTF_KEYUP | KEYEVENTF_SCANCODE, 0, scancode);
}
fn key_down(&mut self, key: Key) {
keybd_event(KEYEVENTF_SCANCODE, 0, self.key_to_scancode(key));
}
fn key_up(&mut self, key: Key) {
keybd_event(
KEYEVENTF_KEYUP | KEYEVENTF_SCANCODE,
0,
self.key_to_scancode(key),
);
}
}
impl Enigo {
/// Gets the (width, height) of the main display in screen coordinates (pixels).
///
/// # Example
///
/// ```no_run
/// use enigo::*;
/// let mut size = Enigo::main_display_size();
/// ```
pub fn main_display_size() -> (usize, usize) {
let w = unsafe { GetSystemMetrics(SM_CXSCREEN) as usize };
let h = unsafe { GetSystemMetrics(SM_CYSCREEN) as usize };
(w, h)
}
/// Gets the location of mouse in screen coordinates (pixels).
///
/// # Example
///
/// ```no_run
/// use enigo::*;
/// let mut location = Enigo::mouse_location();
/// ```
pub fn mouse_location() -> (i32, i32) {
let mut point = POINT { x: 0, y: 0 };
let result = unsafe { GetCursorPos(&mut point) };
if result!= 0 {
(point.x, point.y)
} else {
(0, 0)
}
}
fn unicode_key_click(&self, unicode_char: u16) {
use std::{thread, time};
self.unicode_key_down(unicode_char);
thread::sleep(time::Duration::from_millis(20));
self.unicode_key_up(unicode_char);
}
fn unicode_key_down(&self, unicode_char: u16) {
keybd_event(KEYEVENTF_UNICODE, 0, unicode_char);
}
fn unicode_key_up(&self, unicode_char: u16) {
keybd_event(KEYEVENTF_UNICODE | KEYEVENTF_KEYUP, 0, unicode_char);
}
fn key_to_keycode(&self, key: Key) -> u16 {
// do not use the codes from crate winapi they're
// wrongly typed with i32 instead of i16 use the
// ones provided by win/keycodes.rs that are prefixed
// with an 'E' infront of the original name
#[allow(deprecated)]
// I mean duh, we still need to support deprecated keys until they're removed
match key {
Key::Alt => EVK_MENU,
Key::Backspace => EVK_BACK,
Key::CapsLock => EVK_CAPITAL,
Key::Control => EVK_LCONTROL,
Key::Delete => EVK_DELETE,
Key::DownArrow => EVK_DOWN,
Key::End => EVK_END,
Key::Escape => EVK_ESCAPE,
Key::F1 => EVK_F1,
Key::F10 => EVK_F10,
Key::F11 => EVK_F11,
Key::F12 => EVK_F12,
Key::F2 => EVK_F2,
Key::F3 => EVK_F3,
Key::F4 => EVK_F4,
Key::F5 => EVK_F5,
Key::F6 => EVK_F6,
Key::F7 => EVK_F7,
Key::F8 => EVK_F8,
Key::F9 => EVK_F9,
Key::Home => EVK_HOME,
Key::LeftArrow => EVK_LEFT,
Key::Option => EVK_MENU,
Key::PageDown => EVK_NEXT,
Key::PageUp => EVK_PRIOR,
Key::Return => EVK_RETURN,
Key::RightArrow => EVK_RIGHT,
Key::Shift => EVK_SHIFT,
Key::Space => EVK_SPACE,
Key::Tab => EVK_TAB,
Key::UpArrow => EVK_UP,
Key::Raw(raw_keycode) => raw_keycode,
Key::Layout(c) => self.get_layoutdependent_keycode(c.to_string()),
//_ => 0,
Key::Super | Key::Command | Key::Windows | Key::Meta => EVK_LWIN,
}
}
fn key_to_scancode(&self, key: Key) -> u16 {
let keycode = self.key_to_keycode(key);
unsafe { MapVirtualKeyW(keycode as u32, 0) as u16 }
}
fn get_layoutdependent_keycode(&self, string: String) -> u16 {
let mut buffer = [0; 2];
// get the first char from the string ignore the rest
// ensure its not a multybyte char
let utf16 = string
.chars()
.nth(0)
.expect("no valid input") //TODO(dustin): no panic here make an error
.encode_utf16(&mut buffer);
if utf16.len()!= 1 {
// TODO(dustin) don't panic here use an apropriate errors
panic!("this char is not allowd");
}
// NOTE VkKeyScanW uses the current keyboard layout
// to specify a layout use VkKeyScanExW and GetKeyboardLayout
// or load one with LoadKeyboardLayoutW
let keycode_and_shiftstate = unsafe { VkKeyScanW(utf16[0]) };
// 0x41 as u16 //key that has the letter 'a' on it on english like keylayout
keycode_and_shiftstate as u16
}
}
|
key_click
|
identifier_name
|
win_impl.rs
|
use winapi;
use self::winapi::shared::windef::POINT;
use self::winapi::ctypes::c_int;
use self::winapi::um::winuser::*;
use crate::win::keycodes::*;
use crate::{Key, KeyboardControllable, MouseButton, MouseControllable};
use std::mem::*;
/// The main struct for handling the event emitting
#[derive(Default)]
pub struct Enigo;
fn mouse_event(flags: u32, data: u32, dx: i32, dy: i32) {
let mut input = INPUT {
type_: INPUT_MOUSE,
u: unsafe {
transmute(MOUSEINPUT {
dx,
dy,
mouseData: data,
dwFlags: flags,
time: 0,
dwExtraInfo: 0,
})
},
};
unsafe { SendInput(1, &mut input as LPINPUT, size_of::<INPUT>() as c_int) };
}
fn keybd_event(flags: u32, vk: u16, scan: u16) {
let mut input = INPUT {
type_: INPUT_KEYBOARD,
u: unsafe {
transmute_copy(&KEYBDINPUT {
wVk: vk,
wScan: scan,
dwFlags: flags,
time: 0,
dwExtraInfo: 0,
})
},
};
unsafe { SendInput(1, &mut input as LPINPUT, size_of::<INPUT>() as c_int) };
}
impl MouseControllable for Enigo {
fn mouse_move_to(&mut self, x: i32, y: i32) {
mouse_event(
MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_VIRTUALDESK,
0,
(x - unsafe { GetSystemMetrics(SM_XVIRTUALSCREEN) }) * 65535 / unsafe { GetSystemMetrics(SM_CXVIRTUALSCREEN) },
(y - unsafe { GetSystemMetrics(SM_YVIRTUALSCREEN) }) * 65535 / unsafe { GetSystemMetrics(SM_CYVIRTUALSCREEN) },
);
}
fn mouse_move_relative(&mut self, x: i32, y: i32) {
mouse_event(MOUSEEVENTF_MOVE, 0, x, y);
}
fn mouse_down(&mut self, button: MouseButton) {
mouse_event(
match button {
MouseButton::Left => MOUSEEVENTF_LEFTDOWN,
MouseButton::Middle => MOUSEEVENTF_MIDDLEDOWN,
MouseButton::Right => MOUSEEVENTF_RIGHTDOWN,
_ => unimplemented!(),
},
0,
0,
0,
);
}
fn mouse_up(&mut self, button: MouseButton) {
mouse_event(
match button {
MouseButton::Left => MOUSEEVENTF_LEFTUP,
MouseButton::Middle => MOUSEEVENTF_MIDDLEUP,
MouseButton::Right => MOUSEEVENTF_RIGHTUP,
_ => unimplemented!(),
},
0,
0,
0,
);
}
fn mouse_click(&mut self, button: MouseButton) {
self.mouse_down(button);
self.mouse_up(button);
}
fn mouse_scroll_x(&mut self, length: i32) {
mouse_event(MOUSEEVENTF_HWHEEL, unsafe { transmute(length * 120) }, 0, 0);
}
fn mouse_scroll_y(&mut self, length: i32) {
mouse_event(MOUSEEVENTF_WHEEL, unsafe { transmute(length * 120) }, 0, 0);
}
}
impl KeyboardControllable for Enigo {
fn key_sequence(&mut self, sequence: &str) {
let mut buffer = [0; 2];
for c in sequence.chars() {
// Windows uses uft-16 encoding. We need to check
// for variable length characters. As such some
// characters can be 32 bit long and those are
// encoded in such called hight and low surrogates
// each 16 bit wide that needs to be send after
// another to the SendInput function without
// being interrupted by "keyup"
let result = c.encode_utf16(&mut buffer);
if result.len() == 1 {
self.unicode_key_click(result[0]);
} else
|
}
}
fn key_click(&mut self, key: Key) {
let scancode = self.key_to_scancode(key);
use std::{thread, time};
keybd_event(KEYEVENTF_SCANCODE, 0, scancode);
thread::sleep(time::Duration::from_millis(20));
keybd_event(KEYEVENTF_KEYUP | KEYEVENTF_SCANCODE, 0, scancode);
}
fn key_down(&mut self, key: Key) {
keybd_event(KEYEVENTF_SCANCODE, 0, self.key_to_scancode(key));
}
fn key_up(&mut self, key: Key) {
keybd_event(
KEYEVENTF_KEYUP | KEYEVENTF_SCANCODE,
0,
self.key_to_scancode(key),
);
}
}
impl Enigo {
/// Gets the (width, height) of the main display in screen coordinates (pixels).
///
/// # Example
///
/// ```no_run
/// use enigo::*;
/// let mut size = Enigo::main_display_size();
/// ```
pub fn main_display_size() -> (usize, usize) {
let w = unsafe { GetSystemMetrics(SM_CXSCREEN) as usize };
let h = unsafe { GetSystemMetrics(SM_CYSCREEN) as usize };
(w, h)
}
/// Gets the location of mouse in screen coordinates (pixels).
///
/// # Example
///
/// ```no_run
/// use enigo::*;
/// let mut location = Enigo::mouse_location();
/// ```
pub fn mouse_location() -> (i32, i32) {
let mut point = POINT { x: 0, y: 0 };
let result = unsafe { GetCursorPos(&mut point) };
if result!= 0 {
(point.x, point.y)
} else {
(0, 0)
}
}
fn unicode_key_click(&self, unicode_char: u16) {
use std::{thread, time};
self.unicode_key_down(unicode_char);
thread::sleep(time::Duration::from_millis(20));
self.unicode_key_up(unicode_char);
}
fn unicode_key_down(&self, unicode_char: u16) {
keybd_event(KEYEVENTF_UNICODE, 0, unicode_char);
}
fn unicode_key_up(&self, unicode_char: u16) {
keybd_event(KEYEVENTF_UNICODE | KEYEVENTF_KEYUP, 0, unicode_char);
}
fn key_to_keycode(&self, key: Key) -> u16 {
// do not use the codes from crate winapi they're
// wrongly typed with i32 instead of i16 use the
// ones provided by win/keycodes.rs that are prefixed
// with an 'E' infront of the original name
#[allow(deprecated)]
// I mean duh, we still need to support deprecated keys until they're removed
match key {
Key::Alt => EVK_MENU,
Key::Backspace => EVK_BACK,
Key::CapsLock => EVK_CAPITAL,
Key::Control => EVK_LCONTROL,
Key::Delete => EVK_DELETE,
Key::DownArrow => EVK_DOWN,
Key::End => EVK_END,
Key::Escape => EVK_ESCAPE,
Key::F1 => EVK_F1,
Key::F10 => EVK_F10,
Key::F11 => EVK_F11,
Key::F12 => EVK_F12,
Key::F2 => EVK_F2,
Key::F3 => EVK_F3,
Key::F4 => EVK_F4,
Key::F5 => EVK_F5,
Key::F6 => EVK_F6,
Key::F7 => EVK_F7,
Key::F8 => EVK_F8,
Key::F9 => EVK_F9,
Key::Home => EVK_HOME,
Key::LeftArrow => EVK_LEFT,
Key::Option => EVK_MENU,
Key::PageDown => EVK_NEXT,
Key::PageUp => EVK_PRIOR,
Key::Return => EVK_RETURN,
Key::RightArrow => EVK_RIGHT,
Key::Shift => EVK_SHIFT,
Key::Space => EVK_SPACE,
Key::Tab => EVK_TAB,
Key::UpArrow => EVK_UP,
Key::Raw(raw_keycode) => raw_keycode,
Key::Layout(c) => self.get_layoutdependent_keycode(c.to_string()),
//_ => 0,
Key::Super | Key::Command | Key::Windows | Key::Meta => EVK_LWIN,
}
}
fn key_to_scancode(&self, key: Key) -> u16 {
let keycode = self.key_to_keycode(key);
unsafe { MapVirtualKeyW(keycode as u32, 0) as u16 }
}
fn get_layoutdependent_keycode(&self, string: String) -> u16 {
let mut buffer = [0; 2];
// get the first char from the string ignore the rest
// ensure its not a multybyte char
let utf16 = string
.chars()
.nth(0)
.expect("no valid input") //TODO(dustin): no panic here make an error
.encode_utf16(&mut buffer);
if utf16.len()!= 1 {
// TODO(dustin) don't panic here use an apropriate errors
panic!("this char is not allowd");
}
// NOTE VkKeyScanW uses the current keyboard layout
// to specify a layout use VkKeyScanExW and GetKeyboardLayout
// or load one with LoadKeyboardLayoutW
let keycode_and_shiftstate = unsafe { VkKeyScanW(utf16[0]) };
// 0x41 as u16 //key that has the letter 'a' on it on english like keylayout
keycode_and_shiftstate as u16
}
}
|
{
for utf16_surrogate in result {
self.unicode_key_down(utf16_surrogate.clone());
}
// do i need to produce a keyup?
// self.unicode_key_up(0);
}
|
conditional_block
|
win_impl.rs
|
use winapi;
use self::winapi::shared::windef::POINT;
use self::winapi::ctypes::c_int;
use self::winapi::um::winuser::*;
use crate::win::keycodes::*;
use crate::{Key, KeyboardControllable, MouseButton, MouseControllable};
use std::mem::*;
/// The main struct for handling the event emitting
#[derive(Default)]
pub struct Enigo;
fn mouse_event(flags: u32, data: u32, dx: i32, dy: i32) {
let mut input = INPUT {
type_: INPUT_MOUSE,
u: unsafe {
transmute(MOUSEINPUT {
dx,
dy,
mouseData: data,
dwFlags: flags,
time: 0,
dwExtraInfo: 0,
})
},
};
unsafe { SendInput(1, &mut input as LPINPUT, size_of::<INPUT>() as c_int) };
}
fn keybd_event(flags: u32, vk: u16, scan: u16) {
let mut input = INPUT {
type_: INPUT_KEYBOARD,
u: unsafe {
transmute_copy(&KEYBDINPUT {
wVk: vk,
wScan: scan,
dwFlags: flags,
time: 0,
dwExtraInfo: 0,
})
},
};
unsafe { SendInput(1, &mut input as LPINPUT, size_of::<INPUT>() as c_int) };
}
impl MouseControllable for Enigo {
fn mouse_move_to(&mut self, x: i32, y: i32) {
mouse_event(
MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_VIRTUALDESK,
0,
(x - unsafe { GetSystemMetrics(SM_XVIRTUALSCREEN) }) * 65535 / unsafe { GetSystemMetrics(SM_CXVIRTUALSCREEN) },
(y - unsafe { GetSystemMetrics(SM_YVIRTUALSCREEN) }) * 65535 / unsafe { GetSystemMetrics(SM_CYVIRTUALSCREEN) },
);
}
fn mouse_move_relative(&mut self, x: i32, y: i32) {
mouse_event(MOUSEEVENTF_MOVE, 0, x, y);
}
fn mouse_down(&mut self, button: MouseButton) {
mouse_event(
match button {
MouseButton::Left => MOUSEEVENTF_LEFTDOWN,
MouseButton::Middle => MOUSEEVENTF_MIDDLEDOWN,
MouseButton::Right => MOUSEEVENTF_RIGHTDOWN,
_ => unimplemented!(),
},
0,
0,
0,
);
}
fn mouse_up(&mut self, button: MouseButton) {
mouse_event(
match button {
MouseButton::Left => MOUSEEVENTF_LEFTUP,
MouseButton::Middle => MOUSEEVENTF_MIDDLEUP,
MouseButton::Right => MOUSEEVENTF_RIGHTUP,
_ => unimplemented!(),
},
0,
0,
0,
);
}
fn mouse_click(&mut self, button: MouseButton) {
self.mouse_down(button);
self.mouse_up(button);
}
fn mouse_scroll_x(&mut self, length: i32) {
mouse_event(MOUSEEVENTF_HWHEEL, unsafe { transmute(length * 120) }, 0, 0);
}
fn mouse_scroll_y(&mut self, length: i32) {
mouse_event(MOUSEEVENTF_WHEEL, unsafe { transmute(length * 120) }, 0, 0);
}
}
impl KeyboardControllable for Enigo {
fn key_sequence(&mut self, sequence: &str) {
let mut buffer = [0; 2];
for c in sequence.chars() {
// Windows uses uft-16 encoding. We need to check
// for variable length characters. As such some
// characters can be 32 bit long and those are
// encoded in such called hight and low surrogates
// each 16 bit wide that needs to be send after
// another to the SendInput function without
// being interrupted by "keyup"
let result = c.encode_utf16(&mut buffer);
if result.len() == 1 {
self.unicode_key_click(result[0]);
} else {
for utf16_surrogate in result {
self.unicode_key_down(utf16_surrogate.clone());
}
// do i need to produce a keyup?
// self.unicode_key_up(0);
}
}
}
fn key_click(&mut self, key: Key) {
let scancode = self.key_to_scancode(key);
use std::{thread, time};
keybd_event(KEYEVENTF_SCANCODE, 0, scancode);
thread::sleep(time::Duration::from_millis(20));
keybd_event(KEYEVENTF_KEYUP | KEYEVENTF_SCANCODE, 0, scancode);
}
fn key_down(&mut self, key: Key)
|
fn key_up(&mut self, key: Key) {
keybd_event(
KEYEVENTF_KEYUP | KEYEVENTF_SCANCODE,
0,
self.key_to_scancode(key),
);
}
}
impl Enigo {
/// Gets the (width, height) of the main display in screen coordinates (pixels).
///
/// # Example
///
/// ```no_run
/// use enigo::*;
/// let mut size = Enigo::main_display_size();
/// ```
pub fn main_display_size() -> (usize, usize) {
let w = unsafe { GetSystemMetrics(SM_CXSCREEN) as usize };
let h = unsafe { GetSystemMetrics(SM_CYSCREEN) as usize };
(w, h)
}
/// Gets the location of mouse in screen coordinates (pixels).
///
/// # Example
///
/// ```no_run
/// use enigo::*;
/// let mut location = Enigo::mouse_location();
/// ```
pub fn mouse_location() -> (i32, i32) {
let mut point = POINT { x: 0, y: 0 };
let result = unsafe { GetCursorPos(&mut point) };
if result!= 0 {
(point.x, point.y)
} else {
(0, 0)
}
}
fn unicode_key_click(&self, unicode_char: u16) {
use std::{thread, time};
self.unicode_key_down(unicode_char);
thread::sleep(time::Duration::from_millis(20));
self.unicode_key_up(unicode_char);
}
fn unicode_key_down(&self, unicode_char: u16) {
keybd_event(KEYEVENTF_UNICODE, 0, unicode_char);
}
fn unicode_key_up(&self, unicode_char: u16) {
keybd_event(KEYEVENTF_UNICODE | KEYEVENTF_KEYUP, 0, unicode_char);
}
fn key_to_keycode(&self, key: Key) -> u16 {
// do not use the codes from crate winapi they're
// wrongly typed with i32 instead of i16 use the
// ones provided by win/keycodes.rs that are prefixed
// with an 'E' infront of the original name
#[allow(deprecated)]
// I mean duh, we still need to support deprecated keys until they're removed
match key {
Key::Alt => EVK_MENU,
Key::Backspace => EVK_BACK,
Key::CapsLock => EVK_CAPITAL,
Key::Control => EVK_LCONTROL,
Key::Delete => EVK_DELETE,
Key::DownArrow => EVK_DOWN,
Key::End => EVK_END,
Key::Escape => EVK_ESCAPE,
Key::F1 => EVK_F1,
Key::F10 => EVK_F10,
Key::F11 => EVK_F11,
Key::F12 => EVK_F12,
Key::F2 => EVK_F2,
Key::F3 => EVK_F3,
Key::F4 => EVK_F4,
Key::F5 => EVK_F5,
Key::F6 => EVK_F6,
Key::F7 => EVK_F7,
Key::F8 => EVK_F8,
Key::F9 => EVK_F9,
Key::Home => EVK_HOME,
Key::LeftArrow => EVK_LEFT,
Key::Option => EVK_MENU,
Key::PageDown => EVK_NEXT,
Key::PageUp => EVK_PRIOR,
Key::Return => EVK_RETURN,
Key::RightArrow => EVK_RIGHT,
Key::Shift => EVK_SHIFT,
Key::Space => EVK_SPACE,
Key::Tab => EVK_TAB,
Key::UpArrow => EVK_UP,
Key::Raw(raw_keycode) => raw_keycode,
Key::Layout(c) => self.get_layoutdependent_keycode(c.to_string()),
//_ => 0,
Key::Super | Key::Command | Key::Windows | Key::Meta => EVK_LWIN,
}
}
fn key_to_scancode(&self, key: Key) -> u16 {
let keycode = self.key_to_keycode(key);
unsafe { MapVirtualKeyW(keycode as u32, 0) as u16 }
}
fn get_layoutdependent_keycode(&self, string: String) -> u16 {
let mut buffer = [0; 2];
// get the first char from the string ignore the rest
// ensure its not a multybyte char
let utf16 = string
.chars()
.nth(0)
.expect("no valid input") //TODO(dustin): no panic here make an error
.encode_utf16(&mut buffer);
if utf16.len()!= 1 {
// TODO(dustin) don't panic here use an apropriate errors
panic!("this char is not allowd");
}
// NOTE VkKeyScanW uses the current keyboard layout
// to specify a layout use VkKeyScanExW and GetKeyboardLayout
// or load one with LoadKeyboardLayoutW
let keycode_and_shiftstate = unsafe { VkKeyScanW(utf16[0]) };
// 0x41 as u16 //key that has the letter 'a' on it on english like keylayout
keycode_and_shiftstate as u16
}
}
|
{
keybd_event(KEYEVENTF_SCANCODE, 0, self.key_to_scancode(key));
}
|
identifier_body
|
win_impl.rs
|
use winapi;
use self::winapi::shared::windef::POINT;
use self::winapi::ctypes::c_int;
use self::winapi::um::winuser::*;
use crate::win::keycodes::*;
use crate::{Key, KeyboardControllable, MouseButton, MouseControllable};
use std::mem::*;
/// The main struct for handling the event emitting
#[derive(Default)]
pub struct Enigo;
fn mouse_event(flags: u32, data: u32, dx: i32, dy: i32) {
let mut input = INPUT {
type_: INPUT_MOUSE,
u: unsafe {
transmute(MOUSEINPUT {
dx,
dy,
mouseData: data,
dwFlags: flags,
time: 0,
dwExtraInfo: 0,
})
},
};
unsafe { SendInput(1, &mut input as LPINPUT, size_of::<INPUT>() as c_int) };
}
fn keybd_event(flags: u32, vk: u16, scan: u16) {
let mut input = INPUT {
type_: INPUT_KEYBOARD,
u: unsafe {
transmute_copy(&KEYBDINPUT {
wVk: vk,
wScan: scan,
dwFlags: flags,
time: 0,
dwExtraInfo: 0,
})
},
};
unsafe { SendInput(1, &mut input as LPINPUT, size_of::<INPUT>() as c_int) };
}
impl MouseControllable for Enigo {
fn mouse_move_to(&mut self, x: i32, y: i32) {
mouse_event(
MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_VIRTUALDESK,
0,
(x - unsafe { GetSystemMetrics(SM_XVIRTUALSCREEN) }) * 65535 / unsafe { GetSystemMetrics(SM_CXVIRTUALSCREEN) },
(y - unsafe { GetSystemMetrics(SM_YVIRTUALSCREEN) }) * 65535 / unsafe { GetSystemMetrics(SM_CYVIRTUALSCREEN) },
);
}
fn mouse_move_relative(&mut self, x: i32, y: i32) {
mouse_event(MOUSEEVENTF_MOVE, 0, x, y);
}
fn mouse_down(&mut self, button: MouseButton) {
mouse_event(
match button {
MouseButton::Left => MOUSEEVENTF_LEFTDOWN,
MouseButton::Middle => MOUSEEVENTF_MIDDLEDOWN,
MouseButton::Right => MOUSEEVENTF_RIGHTDOWN,
_ => unimplemented!(),
},
0,
0,
0,
);
}
fn mouse_up(&mut self, button: MouseButton) {
mouse_event(
match button {
MouseButton::Left => MOUSEEVENTF_LEFTUP,
MouseButton::Middle => MOUSEEVENTF_MIDDLEUP,
MouseButton::Right => MOUSEEVENTF_RIGHTUP,
_ => unimplemented!(),
},
0,
0,
0,
);
}
fn mouse_click(&mut self, button: MouseButton) {
self.mouse_down(button);
self.mouse_up(button);
}
fn mouse_scroll_x(&mut self, length: i32) {
mouse_event(MOUSEEVENTF_HWHEEL, unsafe { transmute(length * 120) }, 0, 0);
}
fn mouse_scroll_y(&mut self, length: i32) {
mouse_event(MOUSEEVENTF_WHEEL, unsafe { transmute(length * 120) }, 0, 0);
}
}
impl KeyboardControllable for Enigo {
fn key_sequence(&mut self, sequence: &str) {
let mut buffer = [0; 2];
for c in sequence.chars() {
// Windows uses uft-16 encoding. We need to check
// for variable length characters. As such some
// characters can be 32 bit long and those are
// encoded in such called hight and low surrogates
// each 16 bit wide that needs to be send after
// another to the SendInput function without
// being interrupted by "keyup"
let result = c.encode_utf16(&mut buffer);
if result.len() == 1 {
self.unicode_key_click(result[0]);
} else {
for utf16_surrogate in result {
self.unicode_key_down(utf16_surrogate.clone());
}
// do i need to produce a keyup?
// self.unicode_key_up(0);
}
}
}
fn key_click(&mut self, key: Key) {
let scancode = self.key_to_scancode(key);
use std::{thread, time};
keybd_event(KEYEVENTF_SCANCODE, 0, scancode);
thread::sleep(time::Duration::from_millis(20));
keybd_event(KEYEVENTF_KEYUP | KEYEVENTF_SCANCODE, 0, scancode);
}
fn key_down(&mut self, key: Key) {
keybd_event(KEYEVENTF_SCANCODE, 0, self.key_to_scancode(key));
}
fn key_up(&mut self, key: Key) {
keybd_event(
KEYEVENTF_KEYUP | KEYEVENTF_SCANCODE,
0,
self.key_to_scancode(key),
);
}
}
impl Enigo {
/// Gets the (width, height) of the main display in screen coordinates (pixels).
///
/// # Example
///
/// ```no_run
/// use enigo::*;
/// let mut size = Enigo::main_display_size();
/// ```
pub fn main_display_size() -> (usize, usize) {
let w = unsafe { GetSystemMetrics(SM_CXSCREEN) as usize };
let h = unsafe { GetSystemMetrics(SM_CYSCREEN) as usize };
(w, h)
}
/// Gets the location of mouse in screen coordinates (pixels).
///
/// # Example
///
/// ```no_run
/// use enigo::*;
/// let mut location = Enigo::mouse_location();
/// ```
pub fn mouse_location() -> (i32, i32) {
|
(point.x, point.y)
} else {
(0, 0)
}
}
fn unicode_key_click(&self, unicode_char: u16) {
use std::{thread, time};
self.unicode_key_down(unicode_char);
thread::sleep(time::Duration::from_millis(20));
self.unicode_key_up(unicode_char);
}
fn unicode_key_down(&self, unicode_char: u16) {
keybd_event(KEYEVENTF_UNICODE, 0, unicode_char);
}
fn unicode_key_up(&self, unicode_char: u16) {
keybd_event(KEYEVENTF_UNICODE | KEYEVENTF_KEYUP, 0, unicode_char);
}
fn key_to_keycode(&self, key: Key) -> u16 {
// do not use the codes from crate winapi they're
// wrongly typed with i32 instead of i16 use the
// ones provided by win/keycodes.rs that are prefixed
// with an 'E' infront of the original name
#[allow(deprecated)]
// I mean duh, we still need to support deprecated keys until they're removed
match key {
Key::Alt => EVK_MENU,
Key::Backspace => EVK_BACK,
Key::CapsLock => EVK_CAPITAL,
Key::Control => EVK_LCONTROL,
Key::Delete => EVK_DELETE,
Key::DownArrow => EVK_DOWN,
Key::End => EVK_END,
Key::Escape => EVK_ESCAPE,
Key::F1 => EVK_F1,
Key::F10 => EVK_F10,
Key::F11 => EVK_F11,
Key::F12 => EVK_F12,
Key::F2 => EVK_F2,
Key::F3 => EVK_F3,
Key::F4 => EVK_F4,
Key::F5 => EVK_F5,
Key::F6 => EVK_F6,
Key::F7 => EVK_F7,
Key::F8 => EVK_F8,
Key::F9 => EVK_F9,
Key::Home => EVK_HOME,
Key::LeftArrow => EVK_LEFT,
Key::Option => EVK_MENU,
Key::PageDown => EVK_NEXT,
Key::PageUp => EVK_PRIOR,
Key::Return => EVK_RETURN,
Key::RightArrow => EVK_RIGHT,
Key::Shift => EVK_SHIFT,
Key::Space => EVK_SPACE,
Key::Tab => EVK_TAB,
Key::UpArrow => EVK_UP,
Key::Raw(raw_keycode) => raw_keycode,
Key::Layout(c) => self.get_layoutdependent_keycode(c.to_string()),
//_ => 0,
Key::Super | Key::Command | Key::Windows | Key::Meta => EVK_LWIN,
}
}
fn key_to_scancode(&self, key: Key) -> u16 {
let keycode = self.key_to_keycode(key);
unsafe { MapVirtualKeyW(keycode as u32, 0) as u16 }
}
fn get_layoutdependent_keycode(&self, string: String) -> u16 {
let mut buffer = [0; 2];
// get the first char from the string ignore the rest
// ensure its not a multybyte char
let utf16 = string
.chars()
.nth(0)
.expect("no valid input") //TODO(dustin): no panic here make an error
.encode_utf16(&mut buffer);
if utf16.len()!= 1 {
// TODO(dustin) don't panic here use an apropriate errors
panic!("this char is not allowd");
}
// NOTE VkKeyScanW uses the current keyboard layout
// to specify a layout use VkKeyScanExW and GetKeyboardLayout
// or load one with LoadKeyboardLayoutW
let keycode_and_shiftstate = unsafe { VkKeyScanW(utf16[0]) };
// 0x41 as u16 //key that has the letter 'a' on it on english like keylayout
keycode_and_shiftstate as u16
}
}
|
let mut point = POINT { x: 0, y: 0 };
let result = unsafe { GetCursorPos(&mut point) };
if result != 0 {
|
random_line_split
|
mod.rs
|
use alloc::boxed::Box;
use schemes::{Result, KScheme, Resource, Url};
use syscall::{Error, O_CREAT, ENOENT};
pub use self::dsdt::DSDT;
pub use self::fadt::FADT;
pub use self::madt::MADT;
pub use self::rsdt::RSDT;
pub use self::sdt::SDTHeader;
pub use self::ssdt::SSDT;
pub mod aml;
pub mod dsdt;
pub mod fadt;
pub mod madt;
pub mod rsdt;
pub mod sdt;
pub mod ssdt;
#[derive(Clone, Debug, Default)]
pub struct Acpi {
rsdt: RSDT,
fadt: Option<FADT>,
dsdt: Option<DSDT>,
ssdt: Option<SSDT>,
madt: Option<MADT>,
}
impl Acpi {
pub fn new() -> Option<Box<Self>> {
match RSDT::new() {
Ok(rsdt) => {
// debugln!("{:#?}", rsdt);
let mut acpi = box Acpi {
rsdt: rsdt,
fadt: None,
dsdt: None,
ssdt: None,
madt: None,
};
for addr in acpi.rsdt.addrs.iter() {
let header = unsafe { &*(*addr as *const SDTHeader) };
if let Some(fadt) = FADT::new(header) {
// Why does this hang? debugln!("{:#?}", fadt);
if let Some(dsdt) = DSDT::new(unsafe {
&*(fadt.dsdt as *const SDTHeader)
}) {
// debugln!("DSDT:");
// aml::parse(dsdt.data);
acpi.dsdt = Some(dsdt);
}
acpi.fadt = Some(fadt);
} else if let Some(ssdt) = SSDT::new(header) {
// debugln!("SSDT:");
// aml::parse(ssdt.data);
acpi.ssdt = Some(ssdt);
} else if let Some(madt) = MADT::new(header) {
acpi.madt = Some(madt);
} else {
for b in header.signature.iter() {
debug!("{}", *b as char);
}
debugln!(": Unknown Table");
}
}
Some(acpi)
}
Err(e) => {
debugln!("{}", e);
None
}
}
}
}
|
impl KScheme for Acpi {
fn scheme(&self) -> &str {
"acpi"
}
fn open(&mut self, url: &Url, flags: usize) -> Result<Box<Resource>> {
if url.reference() == "off" && flags & O_CREAT == O_CREAT {
match self.fadt {
Some(fadt) => {
debugln!("Powering Off");
unsafe {
asm!("out dx, ax" : : "{edx}"(fadt.pm1a_control_block), "{ax}"(0 | 1 << 13) : : "intel", "volatile")
};
}
None => {
debugln!("Unable to power off: No FADT");
}
}
}
Err(Error::new(ENOENT))
}
}
|
random_line_split
|
|
mod.rs
|
use alloc::boxed::Box;
use schemes::{Result, KScheme, Resource, Url};
use syscall::{Error, O_CREAT, ENOENT};
pub use self::dsdt::DSDT;
pub use self::fadt::FADT;
pub use self::madt::MADT;
pub use self::rsdt::RSDT;
pub use self::sdt::SDTHeader;
pub use self::ssdt::SSDT;
pub mod aml;
pub mod dsdt;
pub mod fadt;
pub mod madt;
pub mod rsdt;
pub mod sdt;
pub mod ssdt;
#[derive(Clone, Debug, Default)]
pub struct Acpi {
rsdt: RSDT,
fadt: Option<FADT>,
dsdt: Option<DSDT>,
ssdt: Option<SSDT>,
madt: Option<MADT>,
}
impl Acpi {
pub fn new() -> Option<Box<Self>> {
match RSDT::new() {
Ok(rsdt) => {
// debugln!("{:#?}", rsdt);
let mut acpi = box Acpi {
rsdt: rsdt,
fadt: None,
dsdt: None,
ssdt: None,
madt: None,
};
for addr in acpi.rsdt.addrs.iter() {
let header = unsafe { &*(*addr as *const SDTHeader) };
if let Some(fadt) = FADT::new(header) {
// Why does this hang? debugln!("{:#?}", fadt);
if let Some(dsdt) = DSDT::new(unsafe {
&*(fadt.dsdt as *const SDTHeader)
}) {
// debugln!("DSDT:");
// aml::parse(dsdt.data);
acpi.dsdt = Some(dsdt);
}
acpi.fadt = Some(fadt);
} else if let Some(ssdt) = SSDT::new(header) {
// debugln!("SSDT:");
// aml::parse(ssdt.data);
acpi.ssdt = Some(ssdt);
} else if let Some(madt) = MADT::new(header) {
acpi.madt = Some(madt);
} else {
for b in header.signature.iter() {
debug!("{}", *b as char);
}
debugln!(": Unknown Table");
}
}
Some(acpi)
}
Err(e) => {
debugln!("{}", e);
None
}
}
}
}
impl KScheme for Acpi {
fn scheme(&self) -> &str
|
fn open(&mut self, url: &Url, flags: usize) -> Result<Box<Resource>> {
if url.reference() == "off" && flags & O_CREAT == O_CREAT {
match self.fadt {
Some(fadt) => {
debugln!("Powering Off");
unsafe {
asm!("out dx, ax" : : "{edx}"(fadt.pm1a_control_block), "{ax}"(0 | 1 << 13) : : "intel", "volatile")
};
}
None => {
debugln!("Unable to power off: No FADT");
}
}
}
Err(Error::new(ENOENT))
}
}
|
{
"acpi"
}
|
identifier_body
|
mod.rs
|
use alloc::boxed::Box;
use schemes::{Result, KScheme, Resource, Url};
use syscall::{Error, O_CREAT, ENOENT};
pub use self::dsdt::DSDT;
pub use self::fadt::FADT;
pub use self::madt::MADT;
pub use self::rsdt::RSDT;
pub use self::sdt::SDTHeader;
pub use self::ssdt::SSDT;
pub mod aml;
pub mod dsdt;
pub mod fadt;
pub mod madt;
pub mod rsdt;
pub mod sdt;
pub mod ssdt;
#[derive(Clone, Debug, Default)]
pub struct Acpi {
rsdt: RSDT,
fadt: Option<FADT>,
dsdt: Option<DSDT>,
ssdt: Option<SSDT>,
madt: Option<MADT>,
}
impl Acpi {
pub fn new() -> Option<Box<Self>> {
match RSDT::new() {
Ok(rsdt) => {
// debugln!("{:#?}", rsdt);
let mut acpi = box Acpi {
rsdt: rsdt,
fadt: None,
dsdt: None,
ssdt: None,
madt: None,
};
for addr in acpi.rsdt.addrs.iter() {
let header = unsafe { &*(*addr as *const SDTHeader) };
if let Some(fadt) = FADT::new(header) {
// Why does this hang? debugln!("{:#?}", fadt);
if let Some(dsdt) = DSDT::new(unsafe {
&*(fadt.dsdt as *const SDTHeader)
}) {
// debugln!("DSDT:");
// aml::parse(dsdt.data);
acpi.dsdt = Some(dsdt);
}
acpi.fadt = Some(fadt);
} else if let Some(ssdt) = SSDT::new(header) {
// debugln!("SSDT:");
// aml::parse(ssdt.data);
acpi.ssdt = Some(ssdt);
} else if let Some(madt) = MADT::new(header) {
acpi.madt = Some(madt);
} else {
for b in header.signature.iter() {
debug!("{}", *b as char);
}
debugln!(": Unknown Table");
}
}
Some(acpi)
}
Err(e) => {
debugln!("{}", e);
None
}
}
}
}
impl KScheme for Acpi {
fn
|
(&self) -> &str {
"acpi"
}
fn open(&mut self, url: &Url, flags: usize) -> Result<Box<Resource>> {
if url.reference() == "off" && flags & O_CREAT == O_CREAT {
match self.fadt {
Some(fadt) => {
debugln!("Powering Off");
unsafe {
asm!("out dx, ax" : : "{edx}"(fadt.pm1a_control_block), "{ax}"(0 | 1 << 13) : : "intel", "volatile")
};
}
None => {
debugln!("Unable to power off: No FADT");
}
}
}
Err(Error::new(ENOENT))
}
}
|
scheme
|
identifier_name
|
mod.rs
|
use alloc::boxed::Box;
use schemes::{Result, KScheme, Resource, Url};
use syscall::{Error, O_CREAT, ENOENT};
pub use self::dsdt::DSDT;
pub use self::fadt::FADT;
pub use self::madt::MADT;
pub use self::rsdt::RSDT;
pub use self::sdt::SDTHeader;
pub use self::ssdt::SSDT;
pub mod aml;
pub mod dsdt;
pub mod fadt;
pub mod madt;
pub mod rsdt;
pub mod sdt;
pub mod ssdt;
#[derive(Clone, Debug, Default)]
pub struct Acpi {
rsdt: RSDT,
fadt: Option<FADT>,
dsdt: Option<DSDT>,
ssdt: Option<SSDT>,
madt: Option<MADT>,
}
impl Acpi {
pub fn new() -> Option<Box<Self>> {
match RSDT::new() {
Ok(rsdt) => {
// debugln!("{:#?}", rsdt);
let mut acpi = box Acpi {
rsdt: rsdt,
fadt: None,
dsdt: None,
ssdt: None,
madt: None,
};
for addr in acpi.rsdt.addrs.iter() {
let header = unsafe { &*(*addr as *const SDTHeader) };
if let Some(fadt) = FADT::new(header)
|
else if let Some(ssdt) = SSDT::new(header) {
// debugln!("SSDT:");
// aml::parse(ssdt.data);
acpi.ssdt = Some(ssdt);
} else if let Some(madt) = MADT::new(header) {
acpi.madt = Some(madt);
} else {
for b in header.signature.iter() {
debug!("{}", *b as char);
}
debugln!(": Unknown Table");
}
}
Some(acpi)
}
Err(e) => {
debugln!("{}", e);
None
}
}
}
}
impl KScheme for Acpi {
fn scheme(&self) -> &str {
"acpi"
}
fn open(&mut self, url: &Url, flags: usize) -> Result<Box<Resource>> {
if url.reference() == "off" && flags & O_CREAT == O_CREAT {
match self.fadt {
Some(fadt) => {
debugln!("Powering Off");
unsafe {
asm!("out dx, ax" : : "{edx}"(fadt.pm1a_control_block), "{ax}"(0 | 1 << 13) : : "intel", "volatile")
};
}
None => {
debugln!("Unable to power off: No FADT");
}
}
}
Err(Error::new(ENOENT))
}
}
|
{
// Why does this hang? debugln!("{:#?}", fadt);
if let Some(dsdt) = DSDT::new(unsafe {
&*(fadt.dsdt as *const SDTHeader)
}) {
// debugln!("DSDT:");
// aml::parse(dsdt.data);
acpi.dsdt = Some(dsdt);
}
acpi.fadt = Some(fadt);
}
|
conditional_block
|
lib.rs
|
// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(plugin_registrar, rustc_private)]
extern crate syntax;
extern crate rustc;
use syntax::ast::{MetaItem, Expr};
use syntax::ast;
use syntax::codemap::Span;
use syntax::ext::base::{ExtCtxt, Annotatable};
use syntax::ext::build::AstBuilder;
use syntax::ext::deriving::generic::*;
use syntax::ext::deriving::generic::ty::*;
use syntax::parse::token::InternedString;
use syntax::ptr::P;
use syntax::ext::base::MultiDecorator;
use syntax::parse::token;
use rustc::plugin::Registry;
macro_rules! pathvec {
($($x:ident)::+) => (
vec![ $( stringify!($x) ),+ ]
)
}
macro_rules! path {
($($x:tt)*) => (
::syntax::ext::deriving::generic::ty::Path::new( pathvec!( $($x)* ) )
)
}
macro_rules! path_local {
($x:ident) => (
::syntax::ext::deriving::generic::ty::Path::new_local(stringify!($x))
)
}
macro_rules! pathvec_std {
($cx:expr, $first:ident :: $($rest:ident)::+) => (
if $cx.use_std {
pathvec!(std :: $($rest)::+)
} else {
pathvec!($first :: $($rest)::+)
}
)
}
macro_rules! path_std {
($($x:tt)*) => (
::syntax::ext::deriving::generic::ty::Path::new( pathvec_std!( $($x)* ) )
)
}
pub fn expand_deriving_from_primitive(cx: &mut ExtCtxt,
span: Span,
mitem: &MetaItem,
item: &Annotatable,
push: &mut FnMut(Annotatable))
{
let inline = cx.meta_word(span, InternedString::new("inline"));
let attrs = vec!(cx.attribute(span, inline));
let trait_def = TraitDef {
span: span,
attributes: Vec::new(),
path: path!(num::FromPrimitive),
additional_bounds: Vec::new(),
generics: LifetimeBounds::empty(),
methods: vec!(
MethodDef {
name: "from_i64",
is_unsafe: false,
generics: LifetimeBounds::empty(),
explicit_self: None,
args: vec!(Literal(path_local!(i64))),
ret_ty: Literal(Path::new_(pathvec_std!(cx, core::option::Option),
None,
vec!(Box::new(Self_)),
true)),
// #[inline] liable to cause code-bloat
attributes: attrs.clone(),
combine_substructure: combine_substructure(Box::new(|c, s, sub| {
cs_from("i64", c, s, sub)
})),
},
MethodDef {
name: "from_u64",
is_unsafe: false,
generics: LifetimeBounds::empty(),
explicit_self: None,
args: vec!(Literal(path_local!(u64))),
ret_ty: Literal(Path::new_(pathvec_std!(cx, core::option::Option),
None,
vec!(Box::new(Self_)),
true)),
// #[inline] liable to cause code-bloat
attributes: attrs,
combine_substructure: combine_substructure(Box::new(|c, s, sub| {
cs_from("u64", c, s, sub)
})),
}
),
associated_types: Vec::new(),
};
trait_def.expand(cx, mitem, &item, push)
}
fn cs_from(name: &str, cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> P<Expr>
|
for variant in &enum_def.variants {
match variant.node.kind {
ast::TupleVariantKind(ref args) => {
if!args.is_empty() {
cx.span_err(trait_span,
"`FromPrimitive` cannot be derived for \
enum variants with arguments");
return cx.expr_fail(trait_span,
InternedString::new(""));
}
let span = variant.span;
// expr for `$n == $variant as $name`
let path = cx.path(span, vec![substr.type_ident, variant.node.name]);
let variant = cx.expr_path(path);
let ty = cx.ty_ident(span, cx.ident_of(name));
let cast = cx.expr_cast(span, variant.clone(), ty);
let guard = cx.expr_binary(span, ast::BiEq, n.clone(), cast);
// expr for `Some($variant)`
let body = cx.expr_some(span, variant);
// arm for `_ if $guard => $body`
let arm = ast::Arm {
attrs: vec!(),
pats: vec!(cx.pat_wild(span)),
guard: Some(guard),
body: body,
};
arms.push(arm);
}
ast::StructVariantKind(_) => {
cx.span_err(trait_span,
"`FromPrimitive` cannot be derived for enums \
with struct variants");
return cx.expr_fail(trait_span,
InternedString::new(""));
}
}
}
// arm for `_ => None`
let arm = ast::Arm {
attrs: vec!(),
pats: vec!(cx.pat_wild(trait_span)),
guard: None,
body: cx.expr_none(trait_span),
};
arms.push(arm);
cx.expr_match(trait_span, n.clone(), arms)
}
_ => cx.span_bug(trait_span, "expected StaticEnum in derive(FromPrimitive)")
}
}
#[plugin_registrar]
#[doc(hidden)]
pub fn plugin_registrar(reg: &mut Registry) {
reg.register_syntax_extension(
token::intern("derive_NumFromPrimitive"),
MultiDecorator(Box::new(expand_deriving_from_primitive)));
}
|
{
if substr.nonself_args.len() != 1 {
cx.span_bug(trait_span, "incorrect number of arguments in `derive(FromPrimitive)`")
}
let n = &substr.nonself_args[0];
match *substr.fields {
StaticStruct(..) => {
cx.span_err(trait_span, "`FromPrimitive` cannot be derived for structs");
return cx.expr_fail(trait_span, InternedString::new(""));
}
StaticEnum(enum_def, _) => {
if enum_def.variants.is_empty() {
cx.span_err(trait_span,
"`FromPrimitive` cannot be derived for enums with no variants");
return cx.expr_fail(trait_span, InternedString::new(""));
}
let mut arms = Vec::new();
|
identifier_body
|
lib.rs
|
// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(plugin_registrar, rustc_private)]
extern crate syntax;
extern crate rustc;
use syntax::ast::{MetaItem, Expr};
use syntax::ast;
use syntax::codemap::Span;
use syntax::ext::base::{ExtCtxt, Annotatable};
use syntax::ext::build::AstBuilder;
use syntax::ext::deriving::generic::*;
use syntax::ext::deriving::generic::ty::*;
use syntax::parse::token::InternedString;
use syntax::ptr::P;
use syntax::ext::base::MultiDecorator;
use syntax::parse::token;
use rustc::plugin::Registry;
macro_rules! pathvec {
($($x:ident)::+) => (
vec![ $( stringify!($x) ),+ ]
)
}
macro_rules! path {
($($x:tt)*) => (
::syntax::ext::deriving::generic::ty::Path::new( pathvec!( $($x)* ) )
)
}
macro_rules! path_local {
($x:ident) => (
::syntax::ext::deriving::generic::ty::Path::new_local(stringify!($x))
)
}
macro_rules! pathvec_std {
($cx:expr, $first:ident :: $($rest:ident)::+) => (
if $cx.use_std {
pathvec!(std :: $($rest)::+)
} else {
pathvec!($first :: $($rest)::+)
}
)
}
macro_rules! path_std {
($($x:tt)*) => (
::syntax::ext::deriving::generic::ty::Path::new( pathvec_std!( $($x)* ) )
)
}
pub fn expand_deriving_from_primitive(cx: &mut ExtCtxt,
span: Span,
mitem: &MetaItem,
item: &Annotatable,
push: &mut FnMut(Annotatable))
{
let inline = cx.meta_word(span, InternedString::new("inline"));
let attrs = vec!(cx.attribute(span, inline));
let trait_def = TraitDef {
span: span,
attributes: Vec::new(),
path: path!(num::FromPrimitive),
additional_bounds: Vec::new(),
generics: LifetimeBounds::empty(),
methods: vec!(
MethodDef {
name: "from_i64",
is_unsafe: false,
generics: LifetimeBounds::empty(),
explicit_self: None,
args: vec!(Literal(path_local!(i64))),
ret_ty: Literal(Path::new_(pathvec_std!(cx, core::option::Option),
None,
vec!(Box::new(Self_)),
true)),
// #[inline] liable to cause code-bloat
attributes: attrs.clone(),
combine_substructure: combine_substructure(Box::new(|c, s, sub| {
cs_from("i64", c, s, sub)
})),
},
MethodDef {
name: "from_u64",
is_unsafe: false,
generics: LifetimeBounds::empty(),
explicit_self: None,
args: vec!(Literal(path_local!(u64))),
ret_ty: Literal(Path::new_(pathvec_std!(cx, core::option::Option),
None,
vec!(Box::new(Self_)),
true)),
// #[inline] liable to cause code-bloat
attributes: attrs,
combine_substructure: combine_substructure(Box::new(|c, s, sub| {
cs_from("u64", c, s, sub)
})),
}
),
associated_types: Vec::new(),
};
trait_def.expand(cx, mitem, &item, push)
}
fn cs_from(name: &str, cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> P<Expr> {
if substr.nonself_args.len()!= 1 {
cx.span_bug(trait_span, "incorrect number of arguments in `derive(FromPrimitive)`")
}
let n = &substr.nonself_args[0];
match *substr.fields {
StaticStruct(..) =>
|
StaticEnum(enum_def, _) => {
if enum_def.variants.is_empty() {
cx.span_err(trait_span,
"`FromPrimitive` cannot be derived for enums with no variants");
return cx.expr_fail(trait_span, InternedString::new(""));
}
let mut arms = Vec::new();
for variant in &enum_def.variants {
match variant.node.kind {
ast::TupleVariantKind(ref args) => {
if!args.is_empty() {
cx.span_err(trait_span,
"`FromPrimitive` cannot be derived for \
enum variants with arguments");
return cx.expr_fail(trait_span,
InternedString::new(""));
}
let span = variant.span;
// expr for `$n == $variant as $name`
let path = cx.path(span, vec![substr.type_ident, variant.node.name]);
let variant = cx.expr_path(path);
let ty = cx.ty_ident(span, cx.ident_of(name));
let cast = cx.expr_cast(span, variant.clone(), ty);
let guard = cx.expr_binary(span, ast::BiEq, n.clone(), cast);
// expr for `Some($variant)`
let body = cx.expr_some(span, variant);
// arm for `_ if $guard => $body`
let arm = ast::Arm {
attrs: vec!(),
pats: vec!(cx.pat_wild(span)),
guard: Some(guard),
body: body,
};
arms.push(arm);
}
ast::StructVariantKind(_) => {
cx.span_err(trait_span,
"`FromPrimitive` cannot be derived for enums \
with struct variants");
return cx.expr_fail(trait_span,
InternedString::new(""));
}
}
}
// arm for `_ => None`
let arm = ast::Arm {
attrs: vec!(),
pats: vec!(cx.pat_wild(trait_span)),
guard: None,
body: cx.expr_none(trait_span),
};
arms.push(arm);
cx.expr_match(trait_span, n.clone(), arms)
}
_ => cx.span_bug(trait_span, "expected StaticEnum in derive(FromPrimitive)")
}
}
#[plugin_registrar]
#[doc(hidden)]
pub fn plugin_registrar(reg: &mut Registry) {
reg.register_syntax_extension(
token::intern("derive_NumFromPrimitive"),
MultiDecorator(Box::new(expand_deriving_from_primitive)));
}
|
{
cx.span_err(trait_span, "`FromPrimitive` cannot be derived for structs");
return cx.expr_fail(trait_span, InternedString::new(""));
}
|
conditional_block
|
lib.rs
|
// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(plugin_registrar, rustc_private)]
extern crate syntax;
extern crate rustc;
use syntax::ast::{MetaItem, Expr};
use syntax::ast;
use syntax::codemap::Span;
use syntax::ext::base::{ExtCtxt, Annotatable};
use syntax::ext::build::AstBuilder;
use syntax::ext::deriving::generic::*;
use syntax::ext::deriving::generic::ty::*;
use syntax::parse::token::InternedString;
use syntax::ptr::P;
use syntax::ext::base::MultiDecorator;
use syntax::parse::token;
use rustc::plugin::Registry;
macro_rules! pathvec {
($($x:ident)::+) => (
vec![ $( stringify!($x) ),+ ]
)
}
macro_rules! path {
($($x:tt)*) => (
::syntax::ext::deriving::generic::ty::Path::new( pathvec!( $($x)* ) )
)
}
macro_rules! path_local {
($x:ident) => (
::syntax::ext::deriving::generic::ty::Path::new_local(stringify!($x))
)
|
if $cx.use_std {
pathvec!(std :: $($rest)::+)
} else {
pathvec!($first :: $($rest)::+)
}
)
}
macro_rules! path_std {
($($x:tt)*) => (
::syntax::ext::deriving::generic::ty::Path::new( pathvec_std!( $($x)* ) )
)
}
pub fn expand_deriving_from_primitive(cx: &mut ExtCtxt,
span: Span,
mitem: &MetaItem,
item: &Annotatable,
push: &mut FnMut(Annotatable))
{
let inline = cx.meta_word(span, InternedString::new("inline"));
let attrs = vec!(cx.attribute(span, inline));
let trait_def = TraitDef {
span: span,
attributes: Vec::new(),
path: path!(num::FromPrimitive),
additional_bounds: Vec::new(),
generics: LifetimeBounds::empty(),
methods: vec!(
MethodDef {
name: "from_i64",
is_unsafe: false,
generics: LifetimeBounds::empty(),
explicit_self: None,
args: vec!(Literal(path_local!(i64))),
ret_ty: Literal(Path::new_(pathvec_std!(cx, core::option::Option),
None,
vec!(Box::new(Self_)),
true)),
// #[inline] liable to cause code-bloat
attributes: attrs.clone(),
combine_substructure: combine_substructure(Box::new(|c, s, sub| {
cs_from("i64", c, s, sub)
})),
},
MethodDef {
name: "from_u64",
is_unsafe: false,
generics: LifetimeBounds::empty(),
explicit_self: None,
args: vec!(Literal(path_local!(u64))),
ret_ty: Literal(Path::new_(pathvec_std!(cx, core::option::Option),
None,
vec!(Box::new(Self_)),
true)),
// #[inline] liable to cause code-bloat
attributes: attrs,
combine_substructure: combine_substructure(Box::new(|c, s, sub| {
cs_from("u64", c, s, sub)
})),
}
),
associated_types: Vec::new(),
};
trait_def.expand(cx, mitem, &item, push)
}
fn cs_from(name: &str, cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> P<Expr> {
if substr.nonself_args.len()!= 1 {
cx.span_bug(trait_span, "incorrect number of arguments in `derive(FromPrimitive)`")
}
let n = &substr.nonself_args[0];
match *substr.fields {
StaticStruct(..) => {
cx.span_err(trait_span, "`FromPrimitive` cannot be derived for structs");
return cx.expr_fail(trait_span, InternedString::new(""));
}
StaticEnum(enum_def, _) => {
if enum_def.variants.is_empty() {
cx.span_err(trait_span,
"`FromPrimitive` cannot be derived for enums with no variants");
return cx.expr_fail(trait_span, InternedString::new(""));
}
let mut arms = Vec::new();
for variant in &enum_def.variants {
match variant.node.kind {
ast::TupleVariantKind(ref args) => {
if!args.is_empty() {
cx.span_err(trait_span,
"`FromPrimitive` cannot be derived for \
enum variants with arguments");
return cx.expr_fail(trait_span,
InternedString::new(""));
}
let span = variant.span;
// expr for `$n == $variant as $name`
let path = cx.path(span, vec![substr.type_ident, variant.node.name]);
let variant = cx.expr_path(path);
let ty = cx.ty_ident(span, cx.ident_of(name));
let cast = cx.expr_cast(span, variant.clone(), ty);
let guard = cx.expr_binary(span, ast::BiEq, n.clone(), cast);
// expr for `Some($variant)`
let body = cx.expr_some(span, variant);
// arm for `_ if $guard => $body`
let arm = ast::Arm {
attrs: vec!(),
pats: vec!(cx.pat_wild(span)),
guard: Some(guard),
body: body,
};
arms.push(arm);
}
ast::StructVariantKind(_) => {
cx.span_err(trait_span,
"`FromPrimitive` cannot be derived for enums \
with struct variants");
return cx.expr_fail(trait_span,
InternedString::new(""));
}
}
}
// arm for `_ => None`
let arm = ast::Arm {
attrs: vec!(),
pats: vec!(cx.pat_wild(trait_span)),
guard: None,
body: cx.expr_none(trait_span),
};
arms.push(arm);
cx.expr_match(trait_span, n.clone(), arms)
}
_ => cx.span_bug(trait_span, "expected StaticEnum in derive(FromPrimitive)")
}
}
#[plugin_registrar]
#[doc(hidden)]
pub fn plugin_registrar(reg: &mut Registry) {
reg.register_syntax_extension(
token::intern("derive_NumFromPrimitive"),
MultiDecorator(Box::new(expand_deriving_from_primitive)));
}
|
}
macro_rules! pathvec_std {
($cx:expr, $first:ident :: $($rest:ident)::+) => (
|
random_line_split
|
lib.rs
|
// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(plugin_registrar, rustc_private)]
extern crate syntax;
extern crate rustc;
use syntax::ast::{MetaItem, Expr};
use syntax::ast;
use syntax::codemap::Span;
use syntax::ext::base::{ExtCtxt, Annotatable};
use syntax::ext::build::AstBuilder;
use syntax::ext::deriving::generic::*;
use syntax::ext::deriving::generic::ty::*;
use syntax::parse::token::InternedString;
use syntax::ptr::P;
use syntax::ext::base::MultiDecorator;
use syntax::parse::token;
use rustc::plugin::Registry;
macro_rules! pathvec {
($($x:ident)::+) => (
vec![ $( stringify!($x) ),+ ]
)
}
macro_rules! path {
($($x:tt)*) => (
::syntax::ext::deriving::generic::ty::Path::new( pathvec!( $($x)* ) )
)
}
macro_rules! path_local {
($x:ident) => (
::syntax::ext::deriving::generic::ty::Path::new_local(stringify!($x))
)
}
macro_rules! pathvec_std {
($cx:expr, $first:ident :: $($rest:ident)::+) => (
if $cx.use_std {
pathvec!(std :: $($rest)::+)
} else {
pathvec!($first :: $($rest)::+)
}
)
}
macro_rules! path_std {
($($x:tt)*) => (
::syntax::ext::deriving::generic::ty::Path::new( pathvec_std!( $($x)* ) )
)
}
pub fn
|
(cx: &mut ExtCtxt,
span: Span,
mitem: &MetaItem,
item: &Annotatable,
push: &mut FnMut(Annotatable))
{
let inline = cx.meta_word(span, InternedString::new("inline"));
let attrs = vec!(cx.attribute(span, inline));
let trait_def = TraitDef {
span: span,
attributes: Vec::new(),
path: path!(num::FromPrimitive),
additional_bounds: Vec::new(),
generics: LifetimeBounds::empty(),
methods: vec!(
MethodDef {
name: "from_i64",
is_unsafe: false,
generics: LifetimeBounds::empty(),
explicit_self: None,
args: vec!(Literal(path_local!(i64))),
ret_ty: Literal(Path::new_(pathvec_std!(cx, core::option::Option),
None,
vec!(Box::new(Self_)),
true)),
// #[inline] liable to cause code-bloat
attributes: attrs.clone(),
combine_substructure: combine_substructure(Box::new(|c, s, sub| {
cs_from("i64", c, s, sub)
})),
},
MethodDef {
name: "from_u64",
is_unsafe: false,
generics: LifetimeBounds::empty(),
explicit_self: None,
args: vec!(Literal(path_local!(u64))),
ret_ty: Literal(Path::new_(pathvec_std!(cx, core::option::Option),
None,
vec!(Box::new(Self_)),
true)),
// #[inline] liable to cause code-bloat
attributes: attrs,
combine_substructure: combine_substructure(Box::new(|c, s, sub| {
cs_from("u64", c, s, sub)
})),
}
),
associated_types: Vec::new(),
};
trait_def.expand(cx, mitem, &item, push)
}
fn cs_from(name: &str, cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> P<Expr> {
if substr.nonself_args.len()!= 1 {
cx.span_bug(trait_span, "incorrect number of arguments in `derive(FromPrimitive)`")
}
let n = &substr.nonself_args[0];
match *substr.fields {
StaticStruct(..) => {
cx.span_err(trait_span, "`FromPrimitive` cannot be derived for structs");
return cx.expr_fail(trait_span, InternedString::new(""));
}
StaticEnum(enum_def, _) => {
if enum_def.variants.is_empty() {
cx.span_err(trait_span,
"`FromPrimitive` cannot be derived for enums with no variants");
return cx.expr_fail(trait_span, InternedString::new(""));
}
let mut arms = Vec::new();
for variant in &enum_def.variants {
match variant.node.kind {
ast::TupleVariantKind(ref args) => {
if!args.is_empty() {
cx.span_err(trait_span,
"`FromPrimitive` cannot be derived for \
enum variants with arguments");
return cx.expr_fail(trait_span,
InternedString::new(""));
}
let span = variant.span;
// expr for `$n == $variant as $name`
let path = cx.path(span, vec![substr.type_ident, variant.node.name]);
let variant = cx.expr_path(path);
let ty = cx.ty_ident(span, cx.ident_of(name));
let cast = cx.expr_cast(span, variant.clone(), ty);
let guard = cx.expr_binary(span, ast::BiEq, n.clone(), cast);
// expr for `Some($variant)`
let body = cx.expr_some(span, variant);
// arm for `_ if $guard => $body`
let arm = ast::Arm {
attrs: vec!(),
pats: vec!(cx.pat_wild(span)),
guard: Some(guard),
body: body,
};
arms.push(arm);
}
ast::StructVariantKind(_) => {
cx.span_err(trait_span,
"`FromPrimitive` cannot be derived for enums \
with struct variants");
return cx.expr_fail(trait_span,
InternedString::new(""));
}
}
}
// arm for `_ => None`
let arm = ast::Arm {
attrs: vec!(),
pats: vec!(cx.pat_wild(trait_span)),
guard: None,
body: cx.expr_none(trait_span),
};
arms.push(arm);
cx.expr_match(trait_span, n.clone(), arms)
}
_ => cx.span_bug(trait_span, "expected StaticEnum in derive(FromPrimitive)")
}
}
#[plugin_registrar]
#[doc(hidden)]
pub fn plugin_registrar(reg: &mut Registry) {
reg.register_syntax_extension(
token::intern("derive_NumFromPrimitive"),
MultiDecorator(Box::new(expand_deriving_from_primitive)));
}
|
expand_deriving_from_primitive
|
identifier_name
|
lib.rs
|
/* Copyright (C) 2017-2021 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* 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
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
#![cfg_attr(feature = "strict", deny(warnings))]
// Clippy lints we want to suppress due to style, or simply too noisy
// and not a priority right now.
#![allow(clippy::missing_safety_doc)]
#![allow(clippy::needless_return)]
#![allow(clippy::redundant_field_names)]
#![allow(clippy::len_zero)]
#![allow(clippy::too_many_arguments)]
#![allow(clippy::assign_op_pattern)]
#![allow(clippy::manual_range_contains)]
#![allow(clippy::vec_init_then_push)]
#![allow(clippy::assertions_on_constants)]
#![allow(clippy::let_and_return)]
#![allow(clippy::needless_bool)]
#![allow(clippy::char_lit_as_u8)]
// To be fixed, but remove the noise for now.
#![allow(clippy::collapsible_if)]
#![allow(clippy::collapsible_else_if)]
#![allow(clippy::unnecessary_cast)]
#![allow(clippy::redundant_static_lifetimes)]
#![allow(clippy::bool_comparison)]
#![allow(clippy::for_loops_over_fallibles)]
#![allow(clippy::needless_lifetimes)]
#![allow(clippy::single_match)]
#![allow(clippy::upper_case_acronyms)]
#![allow(clippy::ptr_arg)]
#![allow(clippy::new_without_default)]
#![allow(clippy::needless_lifetimes)]
#![allow(clippy::match_ref_pats)]
#![allow(clippy::module_inception)]
#![allow(clippy::needless_range_loop)]
#![allow(clippy::enum_variant_names)]
#![allow(clippy::if_same_then_else)]
#![allow(clippy::match_like_matches_macro)]
#![allow(clippy::extra_unused_lifetimes)]
#![allow(clippy::mixed_case_hex_literals)]
#![allow(clippy::type_complexity)]
#![allow(clippy::nonminimal_bool)]
#![allow(clippy::never_loop)]
#![allow(clippy::large_enum_variant)]
#![allow(clippy::for_loops_over_fallibles)]
#![allow(clippy::explicit_counter_loop)]
#![allow(clippy::branches_sharing_code)]
#![allow(clippy::while_let_loop)]
#![allow(clippy::redundant_pattern_matching)]
#![allow(clippy::field_reassign_with_default)]
#[macro_use]
extern crate nom;
#[macro_use]
extern crate bitflags;
extern crate byteorder;
extern crate crc;
extern crate memchr;
#[macro_use]
extern crate num_derive;
extern crate widestring;
extern crate der_parser;
|
#[macro_use]
extern crate suricata_derive;
#[macro_use]
pub mod log;
#[macro_use]
pub mod core;
#[macro_use]
pub mod common;
pub mod conf;
pub mod jsonbuilder;
#[macro_use]
pub mod applayer;
/// cbindgen:ignore
pub mod frames;
pub mod filecontainer;
pub mod filetracker;
pub mod kerberos;
#[cfg(feature = "lua")]
pub mod lua;
pub mod dns;
pub mod nfs;
pub mod ftp;
pub mod smb;
pub mod krb;
pub mod dcerpc;
pub mod modbus;
pub mod ike;
pub mod snmp;
pub mod ntp;
pub mod tftp;
pub mod dhcp;
pub mod sip;
pub mod rfb;
pub mod mqtt;
pub mod pgsql;
pub mod telnet;
pub mod applayertemplate;
pub mod rdp;
pub mod x509;
pub mod asn1;
pub mod mime;
pub mod ssh;
pub mod http2;
pub mod quic;
pub mod plugin;
pub mod util;
pub mod ffi;
|
extern crate kerberos_parser;
extern crate tls_parser;
extern crate x509_parser;
|
random_line_split
|
error.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Error handling utilities. WIP.
use std::fmt;
use std::fmt::{Debug, Formatter};
use std::old_io::IoError;
pub type CliError = Box<Error +'static>;
pub type CliResult<T> = Result<T, CliError>;
pub type CommandError = Box<Error +'static>;
pub type CommandResult<T> = Result<T, CommandError>;
pub trait Error {
fn description(&self) -> &str;
fn detail(&self) -> Option<&str> { None }
fn cause(&self) -> Option<&Error> { None }
}
pub trait FromError<E> {
fn from_err(err: E) -> Self;
}
impl Debug for Box<Error +'static> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl<E: Error +'static> FromError<E> for Box<Error +'static> {
fn from_err(err: E) -> Box<Error +'static> {
box err as Box<Error>
}
}
impl<'a> Error for &'a str {
fn description<'b>(&'b self) -> &'b str {
*self
}
}
impl Error for String {
fn description<'a>(&'a self) -> &'a str {
&self[]
}
}
impl<'a> Error for Box<Error + 'a> {
fn description(&self) -> &str { (**self).description() }
fn detail(&self) -> Option<&str> { (**self).detail() }
fn cause(&self) -> Option<&Error> { (**self).cause() }
}
impl FromError<()> for () {
fn from_err(_: ()) -> () { () }
}
impl FromError<IoError> for IoError {
fn
|
(error: IoError) -> IoError { error }
}
impl Error for IoError {
fn description(&self) -> &str {
self.desc
}
fn detail(&self) -> Option<&str> {
self.detail.as_ref().map(|s| &s[])
}
}
//fn iter_map_err<T, U, E, I: Iterator<Result<T,E>>>(iter: I,
|
from_err
|
identifier_name
|
error.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Error handling utilities. WIP.
use std::fmt;
use std::fmt::{Debug, Formatter};
use std::old_io::IoError;
pub type CliError = Box<Error +'static>;
pub type CliResult<T> = Result<T, CliError>;
pub type CommandError = Box<Error +'static>;
pub type CommandResult<T> = Result<T, CommandError>;
pub trait Error {
fn description(&self) -> &str;
fn detail(&self) -> Option<&str> { None }
fn cause(&self) -> Option<&Error> { None }
}
pub trait FromError<E> {
fn from_err(err: E) -> Self;
}
impl Debug for Box<Error +'static> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl<E: Error +'static> FromError<E> for Box<Error +'static> {
fn from_err(err: E) -> Box<Error +'static>
|
}
impl<'a> Error for &'a str {
fn description<'b>(&'b self) -> &'b str {
*self
}
}
impl Error for String {
fn description<'a>(&'a self) -> &'a str {
&self[]
}
}
impl<'a> Error for Box<Error + 'a> {
fn description(&self) -> &str { (**self).description() }
fn detail(&self) -> Option<&str> { (**self).detail() }
fn cause(&self) -> Option<&Error> { (**self).cause() }
}
impl FromError<()> for () {
fn from_err(_: ()) -> () { () }
}
impl FromError<IoError> for IoError {
fn from_err(error: IoError) -> IoError { error }
}
impl Error for IoError {
fn description(&self) -> &str {
self.desc
}
fn detail(&self) -> Option<&str> {
self.detail.as_ref().map(|s| &s[])
}
}
//fn iter_map_err<T, U, E, I: Iterator<Result<T,E>>>(iter: I,
|
{
box err as Box<Error>
}
|
identifier_body
|
error.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Error handling utilities. WIP.
use std::fmt;
use std::fmt::{Debug, Formatter};
use std::old_io::IoError;
pub type CliError = Box<Error +'static>;
pub type CliResult<T> = Result<T, CliError>;
pub type CommandError = Box<Error +'static>;
pub type CommandResult<T> = Result<T, CommandError>;
pub trait Error {
fn description(&self) -> &str;
fn detail(&self) -> Option<&str> { None }
fn cause(&self) -> Option<&Error> { None }
}
pub trait FromError<E> {
fn from_err(err: E) -> Self;
}
impl Debug for Box<Error +'static> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl<E: Error +'static> FromError<E> for Box<Error +'static> {
fn from_err(err: E) -> Box<Error +'static> {
box err as Box<Error>
}
}
impl<'a> Error for &'a str {
fn description<'b>(&'b self) -> &'b str {
*self
}
}
impl Error for String {
|
&self[]
}
}
impl<'a> Error for Box<Error + 'a> {
fn description(&self) -> &str { (**self).description() }
fn detail(&self) -> Option<&str> { (**self).detail() }
fn cause(&self) -> Option<&Error> { (**self).cause() }
}
impl FromError<()> for () {
fn from_err(_: ()) -> () { () }
}
impl FromError<IoError> for IoError {
fn from_err(error: IoError) -> IoError { error }
}
impl Error for IoError {
fn description(&self) -> &str {
self.desc
}
fn detail(&self) -> Option<&str> {
self.detail.as_ref().map(|s| &s[])
}
}
//fn iter_map_err<T, U, E, I: Iterator<Result<T,E>>>(iter: I,
|
fn description<'a>(&'a self) -> &'a str {
|
random_line_split
|
ls.rs
|
use std::env;
use std::fs::File;
use std::io;
use chrono::{DateTime, Local};
use fatfs::{FileSystem, FsOptions};
use fscommon::BufStream;
fn format_file_size(size: u64) -> String {
const KB: u64 = 1024;
const MB: u64 = 1024 * KB;
const GB: u64 = 1024 * MB;
if size < KB {
format!("{}B", size)
} else if size < MB {
|
format!("{}KB", size / KB)
} else if size < GB {
format!("{}MB", size / MB)
} else {
format!("{}GB", size / GB)
}
}
fn main() -> io::Result<()> {
let file = File::open("resources/fat32.img")?;
let buf_rdr = BufStream::new(file);
let fs = FileSystem::new(buf_rdr, FsOptions::new())?;
let root_dir = fs.root_dir();
let dir = match env::args().nth(1) {
None => root_dir,
Some(ref path) if path == "." => root_dir,
Some(ref path) => root_dir.open_dir(&path)?,
};
for r in dir.iter() {
let e = r?;
let modified = DateTime::<Local>::from(e.modified())
.format("%Y-%m-%d %H:%M:%S")
.to_string();
println!("{:4} {} {}", format_file_size(e.len()), modified, e.file_name());
}
Ok(())
}
|
random_line_split
|
|
ls.rs
|
use std::env;
use std::fs::File;
use std::io;
use chrono::{DateTime, Local};
use fatfs::{FileSystem, FsOptions};
use fscommon::BufStream;
fn format_file_size(size: u64) -> String {
const KB: u64 = 1024;
const MB: u64 = 1024 * KB;
const GB: u64 = 1024 * MB;
if size < KB {
format!("{}B", size)
} else if size < MB {
format!("{}KB", size / KB)
} else if size < GB {
format!("{}MB", size / MB)
} else {
format!("{}GB", size / GB)
}
}
fn main() -> io::Result<()>
|
{
let file = File::open("resources/fat32.img")?;
let buf_rdr = BufStream::new(file);
let fs = FileSystem::new(buf_rdr, FsOptions::new())?;
let root_dir = fs.root_dir();
let dir = match env::args().nth(1) {
None => root_dir,
Some(ref path) if path == "." => root_dir,
Some(ref path) => root_dir.open_dir(&path)?,
};
for r in dir.iter() {
let e = r?;
let modified = DateTime::<Local>::from(e.modified())
.format("%Y-%m-%d %H:%M:%S")
.to_string();
println!("{:4} {} {}", format_file_size(e.len()), modified, e.file_name());
}
Ok(())
}
|
identifier_body
|
|
ls.rs
|
use std::env;
use std::fs::File;
use std::io;
use chrono::{DateTime, Local};
use fatfs::{FileSystem, FsOptions};
use fscommon::BufStream;
fn format_file_size(size: u64) -> String {
const KB: u64 = 1024;
const MB: u64 = 1024 * KB;
const GB: u64 = 1024 * MB;
if size < KB
|
else if size < MB {
format!("{}KB", size / KB)
} else if size < GB {
format!("{}MB", size / MB)
} else {
format!("{}GB", size / GB)
}
}
fn main() -> io::Result<()> {
let file = File::open("resources/fat32.img")?;
let buf_rdr = BufStream::new(file);
let fs = FileSystem::new(buf_rdr, FsOptions::new())?;
let root_dir = fs.root_dir();
let dir = match env::args().nth(1) {
None => root_dir,
Some(ref path) if path == "." => root_dir,
Some(ref path) => root_dir.open_dir(&path)?,
};
for r in dir.iter() {
let e = r?;
let modified = DateTime::<Local>::from(e.modified())
.format("%Y-%m-%d %H:%M:%S")
.to_string();
println!("{:4} {} {}", format_file_size(e.len()), modified, e.file_name());
}
Ok(())
}
|
{
format!("{}B", size)
}
|
conditional_block
|
ls.rs
|
use std::env;
use std::fs::File;
use std::io;
use chrono::{DateTime, Local};
use fatfs::{FileSystem, FsOptions};
use fscommon::BufStream;
fn
|
(size: u64) -> String {
const KB: u64 = 1024;
const MB: u64 = 1024 * KB;
const GB: u64 = 1024 * MB;
if size < KB {
format!("{}B", size)
} else if size < MB {
format!("{}KB", size / KB)
} else if size < GB {
format!("{}MB", size / MB)
} else {
format!("{}GB", size / GB)
}
}
fn main() -> io::Result<()> {
let file = File::open("resources/fat32.img")?;
let buf_rdr = BufStream::new(file);
let fs = FileSystem::new(buf_rdr, FsOptions::new())?;
let root_dir = fs.root_dir();
let dir = match env::args().nth(1) {
None => root_dir,
Some(ref path) if path == "." => root_dir,
Some(ref path) => root_dir.open_dir(&path)?,
};
for r in dir.iter() {
let e = r?;
let modified = DateTime::<Local>::from(e.modified())
.format("%Y-%m-%d %H:%M:%S")
.to_string();
println!("{:4} {} {}", format_file_size(e.len()), modified, e.file_name());
}
Ok(())
}
|
format_file_size
|
identifier_name
|
varint.rs
|
#![deny(missing_docs)]
use crate::error::*;
use std::io::Read;
const VARINT_MAX_BYTES: usize = 10;
pub fn decode_varint(read: &mut dyn Read) -> Result<u64> {
let mut varint_buf: Vec<u8> = Vec::new();
for i in 0..VARINT_MAX_BYTES {
varint_buf.push(0u8);
match read.read_exact(&mut varint_buf[i..]) {
Ok(_) => (),
Err(e) => return Err(StreamDelimitError::VarintDecodeError(e)),
}
if (varint_buf[i] & 0x80) >> 7!= 0x1 {
let mut concat: u64 = 0;
for i in (0..varint_buf.len()).rev() {
let i_ = i as u32;
concat += u64::from(varint_buf[i] & 0x7f) << (i_ * (8u32.pow(i_) - 1));
}
return Ok(concat);
}
}
Err(StreamDelimitError::VarintDecodeMaxBytesError)
}
pub fn encode_varint(mut value: u64) -> Vec<u8> {
let mut ret = vec![0u8; VARINT_MAX_BYTES];
let mut n = 0;
while value > 127 {
ret[n] = 0x80 | (value & 0x7F) as u8;
value >>= 7;
n += 1
}
ret[n] = value as u8;
n += 1;
ret[0..n].to_vec()
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Cursor;
#[test]
fn test_simple()
|
#[test]
fn test_delimiter_longer() {
assert_eq!(
300,
decode_varint(&mut Cursor::new(encode_varint(300))).unwrap()
);
}
}
|
{
assert_eq!(
1,
decode_varint(&mut Cursor::new(encode_varint(1))).unwrap()
);
}
|
identifier_body
|
varint.rs
|
#![deny(missing_docs)]
use crate::error::*;
use std::io::Read;
const VARINT_MAX_BYTES: usize = 10;
pub fn decode_varint(read: &mut dyn Read) -> Result<u64> {
let mut varint_buf: Vec<u8> = Vec::new();
for i in 0..VARINT_MAX_BYTES {
varint_buf.push(0u8);
match read.read_exact(&mut varint_buf[i..]) {
Ok(_) => (),
Err(e) => return Err(StreamDelimitError::VarintDecodeError(e)),
}
if (varint_buf[i] & 0x80) >> 7!= 0x1 {
let mut concat: u64 = 0;
for i in (0..varint_buf.len()).rev() {
let i_ = i as u32;
concat += u64::from(varint_buf[i] & 0x7f) << (i_ * (8u32.pow(i_) - 1));
}
return Ok(concat);
}
}
Err(StreamDelimitError::VarintDecodeMaxBytesError)
}
pub fn encode_varint(mut value: u64) -> Vec<u8> {
let mut ret = vec![0u8; VARINT_MAX_BYTES];
let mut n = 0;
while value > 127 {
ret[n] = 0x80 | (value & 0x7F) as u8;
value >>= 7;
n += 1
}
ret[n] = value as u8;
n += 1;
ret[0..n].to_vec()
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Cursor;
#[test]
fn
|
() {
assert_eq!(
1,
decode_varint(&mut Cursor::new(encode_varint(1))).unwrap()
);
}
#[test]
fn test_delimiter_longer() {
assert_eq!(
300,
decode_varint(&mut Cursor::new(encode_varint(300))).unwrap()
);
}
}
|
test_simple
|
identifier_name
|
varint.rs
|
#![deny(missing_docs)]
use crate::error::*;
use std::io::Read;
const VARINT_MAX_BYTES: usize = 10;
pub fn decode_varint(read: &mut dyn Read) -> Result<u64> {
let mut varint_buf: Vec<u8> = Vec::new();
for i in 0..VARINT_MAX_BYTES {
varint_buf.push(0u8);
match read.read_exact(&mut varint_buf[i..]) {
Ok(_) => (),
Err(e) => return Err(StreamDelimitError::VarintDecodeError(e)),
}
if (varint_buf[i] & 0x80) >> 7!= 0x1 {
let mut concat: u64 = 0;
for i in (0..varint_buf.len()).rev() {
let i_ = i as u32;
concat += u64::from(varint_buf[i] & 0x7f) << (i_ * (8u32.pow(i_) - 1));
}
return Ok(concat);
}
}
|
pub fn encode_varint(mut value: u64) -> Vec<u8> {
let mut ret = vec![0u8; VARINT_MAX_BYTES];
let mut n = 0;
while value > 127 {
ret[n] = 0x80 | (value & 0x7F) as u8;
value >>= 7;
n += 1
}
ret[n] = value as u8;
n += 1;
ret[0..n].to_vec()
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Cursor;
#[test]
fn test_simple() {
assert_eq!(
1,
decode_varint(&mut Cursor::new(encode_varint(1))).unwrap()
);
}
#[test]
fn test_delimiter_longer() {
assert_eq!(
300,
decode_varint(&mut Cursor::new(encode_varint(300))).unwrap()
);
}
}
|
Err(StreamDelimitError::VarintDecodeMaxBytesError)
}
|
random_line_split
|
job.rs
|
// FIXME: stolen from cargo. Should be extracted into a common crate.
//! Job management (mostly for windows)
//!
//! Most of the time when you're running cargo you expect Ctrl-C to actually
//! terminate the entire tree of processes in play, not just the one at the top
//! (cago). This currently works "by default" on Unix platforms because Ctrl-C
//! actually sends a signal to the *process group* rather than the parent
//! process, so everything will get torn down. On Windows, however, this does
//! not happen and Ctrl-C just kills cargo.
//!
//! To achieve the same semantics on Windows we use Job Objects to ensure that
//! all processes die at the same time. Job objects have a mode of operation
//! where when all handles to the object are closed it causes all child
//! processes associated with the object to be terminated immediately.
//! Conveniently whenever a process in the job object spawns a new process the
//! child will be associated with the job object as well. This means if we add
//! ourselves to the job object we create then everything will get torn down!
#![allow(clippy::missing_safety_doc)]
pub use self::imp::Setup;
pub fn setup() -> Option<Setup> {
unsafe { imp::setup() }
}
#[cfg(unix)]
mod imp {
pub type Setup = ();
pub unsafe fn setup() -> Option<()> {
Some(())
}
}
#[cfg(windows)]
mod imp {
use std::io;
use std::mem;
use std::ptr;
use winapi::shared::minwindef::*;
use winapi::um::handleapi::*;
use winapi::um::jobapi2::*;
use winapi::um::processthreadsapi::*;
use winapi::um::winnt::HANDLE;
use winapi::um::winnt::*;
pub struct Setup {
job: Handle,
}
pub struct Handle {
inner: HANDLE,
}
fn last_err() -> io::Error {
io::Error::last_os_error()
}
pub unsafe fn setup() -> Option<Setup> {
// Creates a new job object for us to use and then adds ourselves to it.
// Note that all errors are basically ignored in this function,
// intentionally. Job objects are "relatively new" in Windows,
// particularly the ability to support nested job objects. Older
// Windows installs don't support this ability. We probably don't want
// to force Cargo to abort in this situation or force others to *not*
// use job objects, so we instead just ignore errors and assume that
// we're otherwise part of someone else's job object in this case.
let job = CreateJobObjectW(ptr::null_mut(), ptr::null());
if job.is_null()
|
let job = Handle { inner: job };
// Indicate that when all handles to the job object are gone that all
// process in the object should be killed. Note that this includes our
// entire process tree by default because we've added ourselves and
// our children will reside in the job once we spawn a process.
let mut info: JOBOBJECT_EXTENDED_LIMIT_INFORMATION;
info = mem::zeroed();
info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
let r = SetInformationJobObject(
job.inner,
JobObjectExtendedLimitInformation,
&mut info as *mut _ as LPVOID,
mem::size_of_val(&info) as DWORD,
);
if r == 0 {
return None;
}
// Assign our process to this job object, meaning that our children will
// now live or die based on our existence.
let me = GetCurrentProcess();
let r = AssignProcessToJobObject(job.inner, me);
if r == 0 {
return None;
}
Some(Setup { job })
}
impl Drop for Setup {
fn drop(&mut self) {
// On normal exits (not ctrl-c), we don't want to kill any child
// processes. The destructor here configures our job object to
// *not* kill everything on close, then closes the job object.
unsafe {
let mut info: JOBOBJECT_EXTENDED_LIMIT_INFORMATION;
info = mem::zeroed();
let r = SetInformationJobObject(
self.job.inner,
JobObjectExtendedLimitInformation,
&mut info as *mut _ as LPVOID,
mem::size_of_val(&info) as DWORD,
);
if r == 0 {
info!("failed to configure job object to defaults: {}", last_err());
}
}
}
}
impl Drop for Handle {
fn drop(&mut self) {
unsafe {
CloseHandle(self.inner);
}
}
}
}
|
{
return None;
}
|
conditional_block
|
job.rs
|
// FIXME: stolen from cargo. Should be extracted into a common crate.
//! Job management (mostly for windows)
//!
//! Most of the time when you're running cargo you expect Ctrl-C to actually
//! terminate the entire tree of processes in play, not just the one at the top
//! (cago). This currently works "by default" on Unix platforms because Ctrl-C
//! actually sends a signal to the *process group* rather than the parent
//! process, so everything will get torn down. On Windows, however, this does
//! not happen and Ctrl-C just kills cargo.
//!
//! To achieve the same semantics on Windows we use Job Objects to ensure that
//! all processes die at the same time. Job objects have a mode of operation
//! where when all handles to the object are closed it causes all child
//! processes associated with the object to be terminated immediately.
//! Conveniently whenever a process in the job object spawns a new process the
//! child will be associated with the job object as well. This means if we add
//! ourselves to the job object we create then everything will get torn down!
#![allow(clippy::missing_safety_doc)]
pub use self::imp::Setup;
pub fn setup() -> Option<Setup> {
unsafe { imp::setup() }
}
#[cfg(unix)]
mod imp {
pub type Setup = ();
pub unsafe fn setup() -> Option<()> {
Some(())
}
}
#[cfg(windows)]
mod imp {
use std::io;
use std::mem;
use std::ptr;
use winapi::shared::minwindef::*;
use winapi::um::handleapi::*;
use winapi::um::jobapi2::*;
use winapi::um::processthreadsapi::*;
use winapi::um::winnt::HANDLE;
use winapi::um::winnt::*;
pub struct
|
{
job: Handle,
}
pub struct Handle {
inner: HANDLE,
}
fn last_err() -> io::Error {
io::Error::last_os_error()
}
pub unsafe fn setup() -> Option<Setup> {
// Creates a new job object for us to use and then adds ourselves to it.
// Note that all errors are basically ignored in this function,
// intentionally. Job objects are "relatively new" in Windows,
// particularly the ability to support nested job objects. Older
// Windows installs don't support this ability. We probably don't want
// to force Cargo to abort in this situation or force others to *not*
// use job objects, so we instead just ignore errors and assume that
// we're otherwise part of someone else's job object in this case.
let job = CreateJobObjectW(ptr::null_mut(), ptr::null());
if job.is_null() {
return None;
}
let job = Handle { inner: job };
// Indicate that when all handles to the job object are gone that all
// process in the object should be killed. Note that this includes our
// entire process tree by default because we've added ourselves and
// our children will reside in the job once we spawn a process.
let mut info: JOBOBJECT_EXTENDED_LIMIT_INFORMATION;
info = mem::zeroed();
info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
let r = SetInformationJobObject(
job.inner,
JobObjectExtendedLimitInformation,
&mut info as *mut _ as LPVOID,
mem::size_of_val(&info) as DWORD,
);
if r == 0 {
return None;
}
// Assign our process to this job object, meaning that our children will
// now live or die based on our existence.
let me = GetCurrentProcess();
let r = AssignProcessToJobObject(job.inner, me);
if r == 0 {
return None;
}
Some(Setup { job })
}
impl Drop for Setup {
fn drop(&mut self) {
// On normal exits (not ctrl-c), we don't want to kill any child
// processes. The destructor here configures our job object to
// *not* kill everything on close, then closes the job object.
unsafe {
let mut info: JOBOBJECT_EXTENDED_LIMIT_INFORMATION;
info = mem::zeroed();
let r = SetInformationJobObject(
self.job.inner,
JobObjectExtendedLimitInformation,
&mut info as *mut _ as LPVOID,
mem::size_of_val(&info) as DWORD,
);
if r == 0 {
info!("failed to configure job object to defaults: {}", last_err());
}
}
}
}
impl Drop for Handle {
fn drop(&mut self) {
unsafe {
CloseHandle(self.inner);
}
}
}
}
|
Setup
|
identifier_name
|
job.rs
|
// FIXME: stolen from cargo. Should be extracted into a common crate.
//! Job management (mostly for windows)
//!
//! Most of the time when you're running cargo you expect Ctrl-C to actually
//! terminate the entire tree of processes in play, not just the one at the top
//! (cago). This currently works "by default" on Unix platforms because Ctrl-C
//! actually sends a signal to the *process group* rather than the parent
//! process, so everything will get torn down. On Windows, however, this does
//! not happen and Ctrl-C just kills cargo.
//!
//! To achieve the same semantics on Windows we use Job Objects to ensure that
//! all processes die at the same time. Job objects have a mode of operation
//! where when all handles to the object are closed it causes all child
//! processes associated with the object to be terminated immediately.
//! Conveniently whenever a process in the job object spawns a new process the
//! child will be associated with the job object as well. This means if we add
//! ourselves to the job object we create then everything will get torn down!
#![allow(clippy::missing_safety_doc)]
pub use self::imp::Setup;
pub fn setup() -> Option<Setup> {
unsafe { imp::setup() }
}
#[cfg(unix)]
mod imp {
pub type Setup = ();
pub unsafe fn setup() -> Option<()> {
Some(())
}
}
#[cfg(windows)]
mod imp {
use std::io;
use std::mem;
use std::ptr;
use winapi::shared::minwindef::*;
use winapi::um::handleapi::*;
use winapi::um::jobapi2::*;
use winapi::um::processthreadsapi::*;
use winapi::um::winnt::HANDLE;
use winapi::um::winnt::*;
pub struct Setup {
job: Handle,
}
pub struct Handle {
inner: HANDLE,
}
fn last_err() -> io::Error {
io::Error::last_os_error()
}
pub unsafe fn setup() -> Option<Setup> {
// Creates a new job object for us to use and then adds ourselves to it.
// Note that all errors are basically ignored in this function,
// intentionally. Job objects are "relatively new" in Windows,
// particularly the ability to support nested job objects. Older
// Windows installs don't support this ability. We probably don't want
// to force Cargo to abort in this situation or force others to *not*
// use job objects, so we instead just ignore errors and assume that
// we're otherwise part of someone else's job object in this case.
let job = CreateJobObjectW(ptr::null_mut(), ptr::null());
if job.is_null() {
return None;
}
let job = Handle { inner: job };
// Indicate that when all handles to the job object are gone that all
// process in the object should be killed. Note that this includes our
// entire process tree by default because we've added ourselves and
// our children will reside in the job once we spawn a process.
let mut info: JOBOBJECT_EXTENDED_LIMIT_INFORMATION;
info = mem::zeroed();
info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
let r = SetInformationJobObject(
job.inner,
JobObjectExtendedLimitInformation,
&mut info as *mut _ as LPVOID,
mem::size_of_val(&info) as DWORD,
);
if r == 0 {
return None;
}
// Assign our process to this job object, meaning that our children will
// now live or die based on our existence.
let me = GetCurrentProcess();
let r = AssignProcessToJobObject(job.inner, me);
if r == 0 {
return None;
}
Some(Setup { job })
}
impl Drop for Setup {
fn drop(&mut self) {
// On normal exits (not ctrl-c), we don't want to kill any child
// processes. The destructor here configures our job object to
// *not* kill everything on close, then closes the job object.
unsafe {
let mut info: JOBOBJECT_EXTENDED_LIMIT_INFORMATION;
|
mem::size_of_val(&info) as DWORD,
);
if r == 0 {
info!("failed to configure job object to defaults: {}", last_err());
}
}
}
}
impl Drop for Handle {
fn drop(&mut self) {
unsafe {
CloseHandle(self.inner);
}
}
}
}
|
info = mem::zeroed();
let r = SetInformationJobObject(
self.job.inner,
JobObjectExtendedLimitInformation,
&mut info as *mut _ as LPVOID,
|
random_line_split
|
job.rs
|
// FIXME: stolen from cargo. Should be extracted into a common crate.
//! Job management (mostly for windows)
//!
//! Most of the time when you're running cargo you expect Ctrl-C to actually
//! terminate the entire tree of processes in play, not just the one at the top
//! (cago). This currently works "by default" on Unix platforms because Ctrl-C
//! actually sends a signal to the *process group* rather than the parent
//! process, so everything will get torn down. On Windows, however, this does
//! not happen and Ctrl-C just kills cargo.
//!
//! To achieve the same semantics on Windows we use Job Objects to ensure that
//! all processes die at the same time. Job objects have a mode of operation
//! where when all handles to the object are closed it causes all child
//! processes associated with the object to be terminated immediately.
//! Conveniently whenever a process in the job object spawns a new process the
//! child will be associated with the job object as well. This means if we add
//! ourselves to the job object we create then everything will get torn down!
#![allow(clippy::missing_safety_doc)]
pub use self::imp::Setup;
pub fn setup() -> Option<Setup>
|
#[cfg(unix)]
mod imp {
pub type Setup = ();
pub unsafe fn setup() -> Option<()> {
Some(())
}
}
#[cfg(windows)]
mod imp {
use std::io;
use std::mem;
use std::ptr;
use winapi::shared::minwindef::*;
use winapi::um::handleapi::*;
use winapi::um::jobapi2::*;
use winapi::um::processthreadsapi::*;
use winapi::um::winnt::HANDLE;
use winapi::um::winnt::*;
pub struct Setup {
job: Handle,
}
pub struct Handle {
inner: HANDLE,
}
fn last_err() -> io::Error {
io::Error::last_os_error()
}
pub unsafe fn setup() -> Option<Setup> {
// Creates a new job object for us to use and then adds ourselves to it.
// Note that all errors are basically ignored in this function,
// intentionally. Job objects are "relatively new" in Windows,
// particularly the ability to support nested job objects. Older
// Windows installs don't support this ability. We probably don't want
// to force Cargo to abort in this situation or force others to *not*
// use job objects, so we instead just ignore errors and assume that
// we're otherwise part of someone else's job object in this case.
let job = CreateJobObjectW(ptr::null_mut(), ptr::null());
if job.is_null() {
return None;
}
let job = Handle { inner: job };
// Indicate that when all handles to the job object are gone that all
// process in the object should be killed. Note that this includes our
// entire process tree by default because we've added ourselves and
// our children will reside in the job once we spawn a process.
let mut info: JOBOBJECT_EXTENDED_LIMIT_INFORMATION;
info = mem::zeroed();
info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
let r = SetInformationJobObject(
job.inner,
JobObjectExtendedLimitInformation,
&mut info as *mut _ as LPVOID,
mem::size_of_val(&info) as DWORD,
);
if r == 0 {
return None;
}
// Assign our process to this job object, meaning that our children will
// now live or die based on our existence.
let me = GetCurrentProcess();
let r = AssignProcessToJobObject(job.inner, me);
if r == 0 {
return None;
}
Some(Setup { job })
}
impl Drop for Setup {
fn drop(&mut self) {
// On normal exits (not ctrl-c), we don't want to kill any child
// processes. The destructor here configures our job object to
// *not* kill everything on close, then closes the job object.
unsafe {
let mut info: JOBOBJECT_EXTENDED_LIMIT_INFORMATION;
info = mem::zeroed();
let r = SetInformationJobObject(
self.job.inner,
JobObjectExtendedLimitInformation,
&mut info as *mut _ as LPVOID,
mem::size_of_val(&info) as DWORD,
);
if r == 0 {
info!("failed to configure job object to defaults: {}", last_err());
}
}
}
}
impl Drop for Handle {
fn drop(&mut self) {
unsafe {
CloseHandle(self.inner);
}
}
}
}
|
{
unsafe { imp::setup() }
}
|
identifier_body
|
group.rs
|
use std::slice;
use std::mem::{ transmute, size_of };
use libc::*;
use ::core::{ Tox, Friend, Group, Peer };
use super::{ ffi };
pub type AvGroupCallback = Fn(Group, Peer, &[i16], u32, u8, u32);
pub trait AvGroupCreate {
fn create_group_av(&self, cb: Box<AvGroupCallback>) -> Result<Group, ()>;
fn join_av(&self, friend: &Friend, data: &[u8], cb: Box<AvGroupCallback>) -> Result<Group, ()>;
|
}
impl AvGroupCreate for Tox {
fn create_group_av(&self, cb: Box<AvGroupCallback>) -> Result<Group, ()> {
match unsafe { ffi::toxav_add_av_groupchat(
transmute(self.core),
on_group_av,
transmute(&cb)
) } {
-1 => Err(()),
num => Ok(Group::from(self.core, num))
}
}
fn join_av(&self, friend: &Friend, data: &[u8], cb: Box<AvGroupCallback>) -> Result<Group, ()> {
match unsafe { ffi::toxav_join_av_groupchat(
transmute(self.core),
friend.number as int32_t,
data.as_ptr(),
data.len() as uint16_t,
on_group_av,
transmute(&cb)
) } {
-1 => Err(()),
num => Ok(Group::from(self.core, num))
}
}
}
extern "C" fn on_group_av(
core: *mut c_void,
group_number: c_int,
peer_number: c_int,
pcm: *const int16_t,
samples: c_uint,
channels: uint8_t,
sample_rate: c_uint,
cb: *mut c_void
) {
unsafe {
let group = Group::from(transmute(core), group_number);
let peer = Peer::from(&group, peer_number);
let callback: &Box<AvGroupCallback> = transmute(cb);
callback(
group,
peer,
slice::from_raw_parts(pcm, samples as usize * channels as usize * size_of::<int16_t>()),
samples,
channels,
sample_rate
);
}
}
|
random_line_split
|
|
group.rs
|
use std::slice;
use std::mem::{ transmute, size_of };
use libc::*;
use ::core::{ Tox, Friend, Group, Peer };
use super::{ ffi };
pub type AvGroupCallback = Fn(Group, Peer, &[i16], u32, u8, u32);
pub trait AvGroupCreate {
fn create_group_av(&self, cb: Box<AvGroupCallback>) -> Result<Group, ()>;
fn join_av(&self, friend: &Friend, data: &[u8], cb: Box<AvGroupCallback>) -> Result<Group, ()>;
}
impl AvGroupCreate for Tox {
fn create_group_av(&self, cb: Box<AvGroupCallback>) -> Result<Group, ()> {
match unsafe { ffi::toxav_add_av_groupchat(
transmute(self.core),
on_group_av,
transmute(&cb)
) } {
-1 => Err(()),
num => Ok(Group::from(self.core, num))
}
}
fn join_av(&self, friend: &Friend, data: &[u8], cb: Box<AvGroupCallback>) -> Result<Group, ()> {
match unsafe { ffi::toxav_join_av_groupchat(
transmute(self.core),
friend.number as int32_t,
data.as_ptr(),
data.len() as uint16_t,
on_group_av,
transmute(&cb)
) } {
-1 => Err(()),
num => Ok(Group::from(self.core, num))
}
}
}
extern "C" fn on_group_av(
core: *mut c_void,
group_number: c_int,
peer_number: c_int,
pcm: *const int16_t,
samples: c_uint,
channels: uint8_t,
sample_rate: c_uint,
cb: *mut c_void
)
|
{
unsafe {
let group = Group::from(transmute(core), group_number);
let peer = Peer::from(&group, peer_number);
let callback: &Box<AvGroupCallback> = transmute(cb);
callback(
group,
peer,
slice::from_raw_parts(pcm, samples as usize * channels as usize * size_of::<int16_t>()),
samples,
channels,
sample_rate
);
}
}
|
identifier_body
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.