Skip to content

Commit 54365e5

Browse files
authored
Merge pull request #56 from yuk1ty/lib-temp_file
feat: lib::env::temp_file を追加
2 parents cbd628e + 1521511 commit 54365e5

File tree

3 files changed

+36
-18
lines changed

3 files changed

+36
-18
lines changed

chapter2/src/2_8_1/main.rs

Lines changed: 2 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,12 @@
11
//! Write format string to a file using `write!` macro (Go version uses `Fprintf`).
22
33
use std::{
4-
env::temp_dir,
54
fmt,
65
fs::File,
76
io::{self, Read, Write},
8-
path::PathBuf,
9-
time::{SystemTime, UNIX_EPOCH},
107
};
118

12-
fn mktemp() -> PathBuf {
13-
let mut tempdir = temp_dir();
14-
15-
let tempfile = {
16-
let now = SystemTime::now();
17-
let unixtime = now
18-
.duration_since(UNIX_EPOCH)
19-
.expect("system clock maybe corrupt");
20-
format!("{}-{:09}", unixtime.as_secs(), unixtime.subsec_nanos())
21-
};
22-
23-
tempdir.push(tempfile);
24-
tempdir
25-
}
9+
use lib::env::temp_file;
2610

2711
fn write_fmt<W: fmt::Write>(w: &mut W) {
2812
write!(
@@ -34,7 +18,7 @@ fn write_fmt<W: fmt::Write>(w: &mut W) {
3418
}
3519

3620
fn main() -> io::Result<()> {
37-
let tmp_path = mktemp();
21+
let tmp_path = temp_file();
3822
{
3923
let mut contents = String::new();
4024
write_fmt(&mut contents);

lib/src/env.rs

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
use std::{
2+
path::PathBuf,
3+
time::{SystemTime, UNIX_EPOCH},
4+
};
5+
6+
/// Returns the path of a temporary file.
7+
///
8+
/// File is never created by calling this function.
9+
///
10+
/// # Examples
11+
///
12+
/// ```
13+
/// use lib::env::temp_file;
14+
///
15+
/// fn main() {
16+
/// let file = temp_file();
17+
/// println!("Temporary file: {}", file.display());
18+
/// }
19+
/// ```
20+
pub fn temp_file() -> PathBuf {
21+
let mut tempdir = std::env::temp_dir();
22+
23+
let tempfile = {
24+
let now = SystemTime::now();
25+
let unixtime = now
26+
.duration_since(UNIX_EPOCH)
27+
.expect("system clock maybe corrupt");
28+
format!("{}-{:09}", unixtime.as_secs(), unixtime.subsec_nanos())
29+
};
30+
31+
tempdir.push(tempfile);
32+
tempdir
33+
}

lib/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
1+
pub mod env;
12
pub mod io;

0 commit comments

Comments
 (0)