ダブルクオテーションを「\"」 に、インデント(4スペース)を「\t」に置き換えます。
もしかしたら置換が必要な文字がまだあるかもしれません。その時は教えていただけると嬉しいです。
コード
main.rs
use std::io::{BufRead, BufReader, BufWriter, Write};
fn read() -> Result<Vec<String>, Box<std::error::Error>> {
let mut ret = Vec::new();
for result in BufReader::new(std::fs::File::open("./01.rs")?).lines() {
let l = result?;
ret.push(l);
}
Ok(ret)
}
fn write(ret: Vec<String>) {
let mut f = BufWriter::new(std::fs::File::create("./01.json").unwrap());
for i in ret {
f.write(i.as_bytes()).unwrap();
}
}
fn main() {
let indent_size = 4; // 偶数である必要あり
if let Ok(lines) = read() {
let mut ss = Vec::new();
for line in lines {
let mut s = String::new();
s.push('"');
let mut cnt = 0;
let mut f = true;
for c in line.chars() {
if c != ' ' {
f = false;
}
if f {
if cnt == 0 {
s.push('\\');
} else if cnt == 1 {
s.push('t');
}
} else {
if c == '"' {
s.push('\\');
s.push('"');
} else if c == '$' {
s.push('\\');
s.push('$');
} else {
s.push(c);
}
}
cnt += 1;
cnt %= indent_size;
}
s.push('"');
s.push(',');
s.push('\n');
ss.push(s);
}
if !ss.is_empty() {
let len = ss.len();
ss[len - 1].pop();
ss[len - 1].pop();
}
write(ss);
} else {
return;
}
}
実行方法
01.rs
から 01.json
を生成します。
.
├── target.json
├── target.rs
├── Cargo.toml
└── src
└── main.rs
実行例
target.rs
trait MOD<T> {
// べき乗余計算アルゴリズム
// a^n mod m を計算する
// "バイナリ法"
fn pow_mod(a: T, n: T, m: T) -> T;
}
impl MOD<i64> for i64 {
fn pow_mod(mut a: i64, mut n: i64, m: i64) -> i64 {
let mut res: i64 = 1;
while n > 0 {
if n & 1 == 1 {
res = res * a % m;
}
a = a * a % m;
n >>= 1;
}
res
}
}
impl MOD<usize> for usize {
fn pow_mod(mut a: usize, mut n: usize, m: usize) -> usize {
let mut res: usize = 1;
while n > 0 {
if n & 1 == 1 {
res = res * a % m;
}
a = a * a % m;
n >>= 1;
}
res
}
}
target.json
"trait MOD<T> {",
"\t// べき乗余計算アルゴリズム",
"\t// a^n mod m を計算する",
"\t// \"バイナリ法\"",
"\tfn pow_mod(a: T, n: T, m: T) -> T;",
"}",
"",
"impl MOD<i64> for i64 {",
"\tfn pow_mod(mut a: i64, mut n: i64, m: i64) -> i64 {",
"\t\tlet mut res: i64 = 1;",
"\t\twhile n > 0 {",
"\t\t\tif n & 1 == 1 {",
"\t\t\t\tres = res * a % m;",
"\t\t\t}",
"\t\t\ta = a * a % m;",
"\t\t\tn >>= 1;",
"\t\t}",
"\t\tres",
"\t}",
"}",
"",
"impl MOD<usize> for usize {",
"\tfn pow_mod(mut a: usize, mut n: usize, m: usize) -> usize {",
"\t\tlet mut res: usize = 1;",
"\t\twhile n > 0 {",
"\t\t\tif n & 1 == 1 {",
"\t\t\t\tres = res * a % m;",
"\t\t\t}",
"\t\t\ta = a * a % m;",
"\t\t\tn >>= 1;",
"\t\t}",
"\t\tres",
"\t}",
"}"