Skip to content

Add an SendStr type #9192

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

Closed
wants to merge 2 commits into from
Closed
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
7 changes: 4 additions & 3 deletions src/libstd/logging.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@
use option::*;
use os;
use rt;
use rt::logging::{Logger, StdErrLogger, OwnedString};
use rt::logging::{Logger, StdErrLogger};
use send_str::SendStrOwned;

/// Turns on logging to stdout globally
pub fn console_on() {
Expand Down Expand Up @@ -56,12 +57,12 @@ fn newsched_log_str(msg: ~str) {
match optional_task {
Some(local) => {
// Use the available logger
(*local).logger.log(OwnedString(msg));
(*local).logger.log(SendStrOwned(msg));
}
None => {
// There is no logger anywhere, just write to stderr
let mut logger = StdErrLogger;
logger.log(OwnedString(msg));
logger.log(SendStrOwned(msg));
}
}
}
Expand Down
1 change: 1 addition & 0 deletions src/libstd/prelude.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ pub use path::PosixPath;
pub use path::WindowsPath;
pub use ptr::RawPtr;
pub use ascii::{Ascii, AsciiCast, OwnedAsciiCast, AsciiStr, ToBytesConsume};
pub use send_str::{SendStr, SendStrOwned, SendStrStatic, IntoSendStr};
pub use str::{Str, StrVector, StrSlice, OwnedStr};
pub use from_str::FromStr;
pub use to_bytes::IterBytes;
Expand Down
15 changes: 5 additions & 10 deletions src/libstd/rt/logging.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ use str::raw::from_c_str;
use u32;
use vec::ImmutableVector;
use cast::transmute;
use send_str::{SendStr, SendStrOwned, SendStrStatic};

struct LogDirective {
name: Option<~str>,
Expand Down Expand Up @@ -168,32 +169,26 @@ fn update_log_settings(crate_map: *u8, settings: ~str) {
}
}

/// Represent a string with `Send` bound.
pub enum SendableString {
OwnedString(~str),
StaticString(&'static str)
}

pub trait Logger {
fn log(&mut self, msg: SendableString);
fn log(&mut self, msg: SendStr);
}

pub struct StdErrLogger;

impl Logger for StdErrLogger {
fn log(&mut self, msg: SendableString) {
fn log(&mut self, msg: SendStr) {
use io::{Writer, WriterUtil};

if !should_log_console() {
return;
}

let s: &str = match msg {
OwnedString(ref s) => {
SendStrOwned(ref s) => {
let slc: &str = *s;
slc
},
StaticString(s) => s,
SendStrStatic(s) => s,
};

// Truncate the string
Expand Down
248 changes: 248 additions & 0 deletions src/libstd/send_str.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,248 @@
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! `SendStr` definition and trait implementations

use clone::{Clone, DeepClone};
use cmp::{Eq, TotalEq, Ord, TotalOrd, Equiv};
use cmp::Ordering;
use container::Container;
use default::Default;
use str::{Str, StrSlice};
use to_str::ToStr;
use to_bytes::{IterBytes, Cb};

/// A SendStr is a string that can hold either a ~str or a &'static str.
/// This can be useful as an optimization when an allocation is sometimes
/// needed but the common case is statically known.
pub enum SendStr {
SendStrOwned(~str),
SendStrStatic(&'static str)
}

impl SendStr {
/// Returns `true` if this `SendStr` wraps an owned string
#[inline]
pub fn is_owned(&self) -> bool {
match *self {
SendStrOwned(_) => true,
SendStrStatic(_) => false
}
}

/// Returns `true` if this `SendStr` wraps an static string
#[inline]
pub fn is_static(&self) -> bool {
match *self {
SendStrOwned(_) => false,
SendStrStatic(_) => true
}
}
}

/// Trait for moving into an `SendStr`
pub trait IntoSendStr {
/// Moves self into an `SendStr`
fn into_send_str(self) -> SendStr;
}

impl IntoSendStr for ~str {
#[inline]
fn into_send_str(self) -> SendStr { SendStrOwned(self) }
}

impl IntoSendStr for &'static str {
#[inline]
fn into_send_str(self) -> SendStr { SendStrStatic(self) }
}

/*
Section: String trait impls.
`SendStr` should behave like a normal string, so we don't derive.
*/

impl ToStr for SendStr {
#[inline]
fn to_str(&self) -> ~str { self.as_slice().to_owned() }
}

impl Eq for SendStr {
#[inline]
fn eq(&self, other: &SendStr) -> bool {
self.as_slice().equals(&other.as_slice())
}
}

impl TotalEq for SendStr {
#[inline]
fn equals(&self, other: &SendStr) -> bool {
self.as_slice().equals(&other.as_slice())
}
}

impl Ord for SendStr {
#[inline]
fn lt(&self, other: &SendStr) -> bool {
self.as_slice().lt(&other.as_slice())
}
}

impl TotalOrd for SendStr {
#[inline]
fn cmp(&self, other: &SendStr) -> Ordering {
self.as_slice().cmp(&other.as_slice())
}
}

impl<'self, S: Str> Equiv<S> for SendStr {
#[inline]
fn equiv(&self, other: &S) -> bool {
self.as_slice().equals(&other.as_slice())
}
}

impl Str for SendStr {
#[inline]
fn as_slice<'r>(&'r self) -> &'r str {
match *self {
SendStrOwned(ref s) => s.as_slice(),
// XXX: Borrowchecker doesn't recognize lifetime as static unless prompted
// SendStrStatic(s) => s.as_slice()
SendStrStatic(s) => {let tmp: &'static str = s; tmp}
}
}

#[inline]
fn into_owned(self) -> ~str {
match self {
SendStrOwned(s) => s,
SendStrStatic(s) => s.to_owned()
}
}
}

impl Container for SendStr {
#[inline]
fn len(&self) -> uint { self.as_slice().len() }
}

impl Clone for SendStr {
#[inline]
fn clone(&self) -> SendStr {
match *self {
SendStrOwned(ref s) => SendStrOwned(s.to_owned()),
SendStrStatic(s) => SendStrStatic(s)
}
}
}

impl DeepClone for SendStr {
#[inline]
fn deep_clone(&self) -> SendStr {
match *self {
SendStrOwned(ref s) => SendStrOwned(s.to_owned()),
SendStrStatic(s) => SendStrStatic(s)
}
}
}

impl Default for SendStr {
#[inline]
fn default() -> SendStr { SendStrStatic("") }
}

impl IterBytes for SendStr {
#[inline]
fn iter_bytes(&self, lsb0: bool, f: Cb) -> bool {
match *self {
SendStrOwned(ref s) => s.iter_bytes(lsb0, f),
SendStrStatic(s) => s.iter_bytes(lsb0, f)
}
}
}

#[cfg(test)]
mod tests {
use clone::{Clone, DeepClone};
use cmp::{TotalEq, Ord, TotalOrd, Equiv};
use cmp::Equal;
use container::Container;
use default::Default;
use send_str::{SendStrOwned, SendStrStatic};
use str::Str;
use to_str::ToStr;

#[test]
fn test_send_str_traits() {
let s = SendStrStatic("abcde");
assert_eq!(s.len(), 5);
assert_eq!(s.as_slice(), "abcde");
assert_eq!(s.to_str(), ~"abcde");
assert!(s.equiv(&@"abcde"));
assert!(s.lt(&SendStrOwned(~"bcdef")));
assert_eq!(SendStrStatic(""), Default::default());

let o = SendStrOwned(~"abcde");
assert_eq!(o.len(), 5);
assert_eq!(o.as_slice(), "abcde");
assert_eq!(o.to_str(), ~"abcde");
assert!(o.equiv(&@"abcde"));
assert!(o.lt(&SendStrStatic("bcdef")));
assert_eq!(SendStrOwned(~""), Default::default());

assert_eq!(s.cmp(&o), Equal);
assert!(s.equals(&o));
assert!(s.equiv(&o));

assert_eq!(o.cmp(&s), Equal);
assert!(o.equals(&s));
assert!(o.equiv(&s));
}

#[test]
fn test_send_str_methods() {
let s = SendStrStatic("abcde");
assert!(s.is_static());
assert!(!s.is_owned());

let o = SendStrOwned(~"abcde");
assert!(!o.is_static());
assert!(o.is_owned());
}

#[test]
fn test_send_str_clone() {
assert_eq!(SendStrOwned(~"abcde"), SendStrStatic("abcde").clone());
assert_eq!(SendStrOwned(~"abcde"), SendStrStatic("abcde").deep_clone());

assert_eq!(SendStrOwned(~"abcde"), SendStrOwned(~"abcde").clone());
assert_eq!(SendStrOwned(~"abcde"), SendStrOwned(~"abcde").deep_clone());

assert_eq!(SendStrStatic("abcde"), SendStrStatic("abcde").clone());
assert_eq!(SendStrStatic("abcde"), SendStrStatic("abcde").deep_clone());

assert_eq!(SendStrStatic("abcde"), SendStrOwned(~"abcde").clone());
assert_eq!(SendStrStatic("abcde"), SendStrOwned(~"abcde").deep_clone());
}

#[test]
fn test_send_str_into_owned() {
assert_eq!(SendStrStatic("abcde").into_owned(), ~"abcde");
assert_eq!(SendStrOwned(~"abcde").into_owned(), ~"abcde");
}

#[test]
fn test_into_send_str() {
assert_eq!("abcde".into_send_str(), SendStrStatic("abcde"));
assert_eq!((~"abcde").into_send_str(), SendStrStatic("abcde"));
assert_eq!("abcde".into_send_str(), SendStrOwned(~"abcde"));
assert_eq!((~"abcde").into_send_str(), SendStrOwned(~"abcde"));
}
}
1 change: 1 addition & 0 deletions src/libstd/std.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@ pub mod str;

#[path = "str/ascii.rs"]
pub mod ascii;
pub mod send_str;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can this go in str/send_str.rs?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To be honest I'm unsure if grouping similar module in their own subfolders is actually desired - As is it doesn't match the way module source file lookup looks for them (hence the path attribute).

I originally introduced that str folder together with ascii.rs when I understood the module system far less than today. The only other modules that do this are the modules in the num directory (also introduced by me :| ), but those at least have the excuse of being horrible repetitive and macro generated.

If grouping string related modules into their own directory is desirable, even if it doesn't mirror the way module hierarchy source file lookup works, then I'd have to make a separate commit for also moving a bunch of other modules anyway to be consistent. Maybe I should make an issue about this.


pub mod ptr;
pub mod owned;
Expand Down
Loading