Skip to content

std: Modernize the local_data api #13835

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 8, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 33 additions & 37 deletions src/libcollections/hashmap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1617,8 +1617,7 @@ mod test_map {
use std::cmp::Equiv;
use std::hash::Hash;
use std::iter::{Iterator,range_inclusive,range_step_inclusive};
use std::local_data;
use std::vec;
use std::cell::RefCell;

struct KindaIntLike(int);

Expand Down Expand Up @@ -1657,7 +1656,7 @@ mod test_map {
assert_eq!(*m.find(&2).unwrap(), 4);
}

local_data_key!(drop_vector: vec::Vec<int>)
local_data_key!(drop_vector: RefCell<Vec<int>>)

#[deriving(Hash, Eq, TotalEq)]
struct Dropable {
Expand All @@ -1667,75 +1666,72 @@ mod test_map {

impl Dropable {
fn new(k: uint) -> Dropable {
local_data::get_mut(drop_vector,
|v| { v.unwrap().as_mut_slice()[k] += 1; });
let v = drop_vector.get().unwrap();
v.borrow_mut().as_mut_slice()[k] += 1;

Dropable { k: k }
}
}

impl Drop for Dropable {
fn drop(&mut self) {
local_data::get_mut(drop_vector, |v|
{ v.unwrap().as_mut_slice()[self.k] -= 1; });
let v = drop_vector.get().unwrap();
v.borrow_mut().as_mut_slice()[self.k] -= 1;
}
}

#[test]
fn test_drops() {
local_data::set(drop_vector, vec::Vec::from_elem(200, 0));
drop_vector.replace(Some(RefCell::new(Vec::from_elem(200, 0))));

{
let mut m = HashMap::new();

local_data::get(drop_vector, |v| {
for i in range(0u, 200) {
assert_eq!(v.unwrap().as_slice()[i], 0);
}
});
let v = drop_vector.get().unwrap();
for i in range(0u, 200) {
assert_eq!(v.borrow().as_slice()[i], 0);
}
drop(v);

for i in range(0u, 100) {
let d1 = Dropable::new(i);
let d2 = Dropable::new(i+100);
m.insert(d1, d2);
}

local_data::get(drop_vector, |v| {
for i in range(0u, 200) {
assert_eq!(v.unwrap().as_slice()[i], 1);
}
});
let v = drop_vector.get().unwrap();
for i in range(0u, 200) {
assert_eq!(v.borrow().as_slice()[i], 1);
}
drop(v);

for i in range(0u, 50) {
let k = Dropable::new(i);
let v = m.pop(&k);

assert!(v.is_some());

local_data::get(drop_vector, |v| {
assert_eq!(v.unwrap().as_slice()[i], 1);
assert_eq!(v.unwrap().as_slice()[i+100], 1);
});
let v = drop_vector.get().unwrap();
assert_eq!(v.borrow().as_slice()[i], 1);
assert_eq!(v.borrow().as_slice()[i+100], 1);
}

local_data::get(drop_vector, |v| {
for i in range(0u, 50) {
assert_eq!(v.unwrap().as_slice()[i], 0);
assert_eq!(v.unwrap().as_slice()[i+100], 0);
}
let v = drop_vector.get().unwrap();
for i in range(0u, 50) {
assert_eq!(v.borrow().as_slice()[i], 0);
assert_eq!(v.borrow().as_slice()[i+100], 0);
}

for i in range(50u, 100) {
assert_eq!(v.unwrap().as_slice()[i], 1);
assert_eq!(v.unwrap().as_slice()[i+100], 1);
}
});
for i in range(50u, 100) {
assert_eq!(v.borrow().as_slice()[i], 1);
assert_eq!(v.borrow().as_slice()[i+100], 1);
}
}

local_data::get(drop_vector, |v| {
for i in range(0u, 200) {
assert_eq!(v.unwrap().as_slice()[i], 0);
}
});
let v = drop_vector.get().unwrap();
for i in range(0u, 200) {
assert_eq!(v.borrow().as_slice()[i], 0);
}
}

#[test]
Expand Down
9 changes: 3 additions & 6 deletions src/liblog/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,6 @@ use std::cast;
use std::fmt;
use std::io::LineBufferedWriter;
use std::io;
use std::local_data;
use std::os;
use std::rt;
use std::slice;
Expand Down Expand Up @@ -228,7 +227,7 @@ pub fn log(level: u32, loc: &'static LogLocation, args: &fmt::Arguments) {
// Completely remove the local logger from TLS in case anyone attempts to
// frob the slot while we're doing the logging. This will destroy any logger
// set during logging.
let mut logger = local_data::pop(local_logger).unwrap_or_else(|| {
let mut logger = local_logger.replace(None).unwrap_or_else(|| {
box DefaultLogger { handle: io::stderr() } as Box<Logger:Send>
});
logger.log(&LogRecord {
Expand All @@ -238,7 +237,7 @@ pub fn log(level: u32, loc: &'static LogLocation, args: &fmt::Arguments) {
module_path: loc.module_path,
line: loc.line,
});
local_data::set(local_logger, logger);
local_logger.replace(Some(logger));
}

/// Getter for the global log level. This is a function so that it can be called
Expand All @@ -250,9 +249,7 @@ pub fn log_level() -> u32 { unsafe { LOG_LEVEL } }
/// Replaces the task-local logger with the specified logger, returning the old
/// logger.
pub fn set_logger(logger: Box<Logger:Send>) -> Option<Box<Logger:Send>> {
let prev = local_data::pop(local_logger);
local_data::set(local_logger, logger);
return prev;
local_logger.replace(Some(logger))
}

/// A LogRecord is created by the logging macros, and passed as the only
Expand Down
18 changes: 10 additions & 8 deletions src/librand/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,6 @@ println!("{:?}", tuple_ptr)
use std::cast;
use std::io::IoResult;
use std::kinds::marker;
use std::local_data;
use std::strbuf::StrBuf;

pub use isaac::{IsaacRng, Isaac64Rng};
Expand Down Expand Up @@ -581,9 +580,6 @@ pub struct TaskRng {
marker: marker::NoSend,
}

// used to make space in TLS for a random number generator
local_data_key!(TASK_RNG_KEY: Box<TaskRngInner>)

/// Retrieve the lazily-initialized task-local random number
/// generator, seeded by the system. Intended to be used in method
/// chaining style, e.g. `task_rng().gen::<int>()`.
Expand All @@ -596,7 +592,10 @@ local_data_key!(TASK_RNG_KEY: Box<TaskRngInner>)
/// the same sequence always. If absolute consistency is required,
/// explicitly select an RNG, e.g. `IsaacRng` or `Isaac64Rng`.
pub fn task_rng() -> TaskRng {
local_data::get_mut(TASK_RNG_KEY, |rng| match rng {
// used to make space in TLS for a random number generator
local_data_key!(TASK_RNG_KEY: Box<TaskRngInner>)

match TASK_RNG_KEY.get() {
None => {
let r = match StdRng::new() {
Ok(r) => r,
Expand All @@ -607,12 +606,15 @@ pub fn task_rng() -> TaskRng {
TaskRngReseeder);
let ptr = &mut *rng as *mut TaskRngInner;

local_data::set(TASK_RNG_KEY, rng);
TASK_RNG_KEY.replace(Some(rng));

TaskRng { rng: ptr, marker: marker::NoSend }
}
Some(rng) => TaskRng { rng: &mut **rng, marker: marker::NoSend }
})
Some(rng) => TaskRng {
rng: &**rng as *_ as *mut TaskRngInner,
marker: marker::NoSend
}
}
}

impl Rng for TaskRng {
Expand Down
35 changes: 14 additions & 21 deletions src/librustc/middle/trans/base.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,6 @@ use arena::TypedArena;
use libc::c_uint;
use std::c_str::ToCStr;
use std::cell::{Cell, RefCell};
use std::local_data;
use std::rc::Rc;
use syntax::abi::{X86, X86_64, Arm, Mips, Rust, RustIntrinsic};
use syntax::ast_util::{local_def, is_local};
Expand All @@ -88,43 +87,37 @@ use syntax::{ast, ast_util, ast_map};

use time;

local_data_key!(task_local_insn_key: Vec<&'static str> )
local_data_key!(task_local_insn_key: RefCell<Vec<&'static str>>)

pub fn with_insn_ctxt(blk: |&[&'static str]|) {
local_data::get(task_local_insn_key, |c| {
match c {
Some(ctx) => blk(ctx.as_slice()),
None => ()
}
})
match task_local_insn_key.get() {
Some(ctx) => blk(ctx.borrow().as_slice()),
None => ()
}
}

pub fn init_insn_ctxt() {
local_data::set(task_local_insn_key, Vec::new());
task_local_insn_key.replace(Some(RefCell::new(Vec::new())));
}

pub struct _InsnCtxt { _x: () }

#[unsafe_destructor]
impl Drop for _InsnCtxt {
fn drop(&mut self) {
local_data::modify(task_local_insn_key, |c| {
c.map(|mut ctx| {
ctx.pop();
ctx
})
})
match task_local_insn_key.get() {
Some(ctx) => { ctx.borrow_mut().pop(); }
None => {}
}
}
}

pub fn push_ctxt(s: &'static str) -> _InsnCtxt {
debug!("new InsnCtxt: {}", s);
local_data::modify(task_local_insn_key, |c| {
c.map(|mut ctx| {
ctx.push(s);
ctx
})
});
match task_local_insn_key.get() {
Some(ctx) => ctx.borrow_mut().push(s),
None => {}
}
_InsnCtxt { _x: () }
}

Expand Down
8 changes: 3 additions & 5 deletions src/librustc/util/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,23 +14,21 @@ use syntax::ast;
use syntax::visit;
use syntax::visit::Visitor;

use std::local_data;

use time;

pub fn time<T, U>(do_it: bool, what: &str, u: U, f: |U| -> T) -> T {
local_data_key!(depth: uint);
if !do_it { return f(u); }

let old = local_data::get(depth, |d| d.map(|a| *a).unwrap_or(0));
local_data::set(depth, old + 1);
let old = depth.get().map(|d| *d).unwrap_or(0);
depth.replace(Some(old + 1));

let start = time::precise_time_s();
let rv = f(u);
let end = time::precise_time_s();

println!("{}time: {:3.3f} s\t{}", " ".repeat(old), end - start, what);
local_data::set(depth, old);
depth.replace(Some(old));

rv
}
Expand Down
15 changes: 7 additions & 8 deletions src/librustdoc/clean.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ use rustc::metadata::cstore;
use rustc::metadata::csearch;
use rustc::metadata::decoder;

use std::local_data;
use std::strbuf::StrBuf;

use core;
Expand Down Expand Up @@ -77,7 +76,7 @@ pub struct Crate {

impl<'a> Clean<Crate> for visit_ast::RustdocVisitor<'a> {
fn clean(&self) -> Crate {
let cx = local_data::get(super::ctxtkey, |x| *x.unwrap());
let cx = super::ctxtkey.get().unwrap();

let mut externs = Vec::new();
cx.sess().cstore.iter_crate_data(|n, meta| {
Expand Down Expand Up @@ -251,7 +250,7 @@ impl Clean<Item> for doctree::Module {
// determine if we should display the inner contents or
// the outer `mod` item for the source code.
let where = {
let ctxt = local_data::get(super::ctxtkey, |x| *x.unwrap());
let ctxt = super::ctxtkey.get().unwrap();
let cm = ctxt.sess().codemap();
let outer = cm.lookup_char_pos(self.where_outer.lo);
let inner = cm.lookup_char_pos(self.where_inner.lo);
Expand Down Expand Up @@ -726,7 +725,7 @@ impl Clean<Type> for ast::Ty {
fn clean(&self) -> Type {
use syntax::ast::*;
debug!("cleaning type `{:?}`", self);
let ctxt = local_data::get(super::ctxtkey, |x| *x.unwrap());
let ctxt = super::ctxtkey.get().unwrap();
let codemap = ctxt.sess().codemap();
debug!("span corresponds to `{}`", codemap.span_to_str(self.span));
match self.node {
Expand Down Expand Up @@ -909,7 +908,7 @@ pub struct Span {

impl Clean<Span> for syntax::codemap::Span {
fn clean(&self) -> Span {
let ctxt = local_data::get(super::ctxtkey, |x| *x.unwrap());
let ctxt = super::ctxtkey.get().unwrap();
let cm = ctxt.sess().codemap();
let filename = cm.span_to_filename(*self);
let lo = cm.lookup_char_pos(self.lo);
Expand Down Expand Up @@ -1237,7 +1236,7 @@ trait ToSource {
impl ToSource for syntax::codemap::Span {
fn to_src(&self) -> ~str {
debug!("converting span {:?} to snippet", self.clean());
let ctxt = local_data::get(super::ctxtkey, |x| x.unwrap().clone());
let ctxt = super::ctxtkey.get().unwrap();
let cm = ctxt.sess().codemap().clone();
let sn = match cm.span_to_snippet(*self) {
Some(x) => x,
Expand Down Expand Up @@ -1292,7 +1291,7 @@ fn name_from_pat(p: &ast::Pat) -> ~str {
/// Given a Type, resolve it using the def_map
fn resolve_type(path: Path, tpbs: Option<Vec<TyParamBound> >,
id: ast::NodeId) -> Type {
let cx = local_data::get(super::ctxtkey, |x| *x.unwrap());
let cx = super::ctxtkey.get().unwrap();
let tycx = match cx.maybe_typed {
core::Typed(ref tycx) => tycx,
// If we're extracting tests, this return value doesn't matter.
Expand Down Expand Up @@ -1351,7 +1350,7 @@ fn resolve_use_source(path: Path, id: ast::NodeId) -> ImportSource {
}

fn resolve_def(id: ast::NodeId) -> Option<ast::DefId> {
let cx = local_data::get(super::ctxtkey, |x| *x.unwrap());
let cx = super::ctxtkey.get().unwrap();
match cx.maybe_typed {
core::Typed(ref tcx) => {
tcx.def_map.borrow().find(&id).map(|&d| ast_util::def_id_of_def(d))
Expand Down
3 changes: 1 addition & 2 deletions src/librustdoc/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ use syntax;

use std::cell::RefCell;
use std::os;
use std::local_data;
use collections::HashSet;

use visit_ast::RustdocVisitor;
Expand Down Expand Up @@ -109,7 +108,7 @@ pub fn run_core(libs: HashSet<Path>, cfgs: Vec<~str>, path: &Path)
-> (clean::Crate, CrateAnalysis) {
let (ctxt, analysis) = get_ast_and_resolve(path, libs, cfgs);
let ctxt = @ctxt;
local_data::set(super::ctxtkey, ctxt);
super::ctxtkey.replace(Some(ctxt));

let krate = {
let mut v = RustdocVisitor::new(ctxt, Some(&analysis));
Expand Down
Loading