summaryrefslogtreecommitdiffstats
path: root/src/args.rs
diff options
context:
space:
mode:
authorAndrew Gallant <jamslam@gmail.com>2017-03-08 20:22:48 -0500
committerAndrew Gallant <jamslam@gmail.com>2017-03-12 19:54:48 -0400
commit8bbe58d623db78a32b04eabff9a69667ad23ff7b (patch)
treef37d62299c50366c0eb8e619cc043f9feb4ba573 /src/args.rs
parentb3fd0df94bbf928ea00cf9a10bd007f4b236d85b (diff)
Add support for additional text encodings.
This includes, but is not limited to, UTF-16, latin-1, GBK, EUC-JP and Shift_JIS. (Courtesy of the `encoding_rs` crate.) Specifically, this feature enables ripgrep to search files that are encoded in an encoding other than UTF-8. The list of available encodings is tied directly to what the `encoding_rs` crate supports, which is in turn tied to the Encoding Standard. The full list of available encodings can be found here: https://encoding.spec.whatwg.org/#concept-encoding-get This pull request also introduces the notion that text encodings can be automatically detected on a best effort basis. Currently, the only support for this is checking for a UTF-16 bom. In all other cases, a text encoding of `auto` (the default) implies a UTF-8 or ASCII compatible source encoding. When a text encoding is otherwise specified, it is unconditionally used for all files searched. Since ripgrep's regex engine is fundamentally built on top of UTF-8, this feature works by transcoding the files to be searched from their source encoding to UTF-8. This transcoding only happens when: 1. `auto` is specified and a non-UTF-8 encoding is detected. 2. A specific encoding is given by end users (including UTF-8). When transcoding occurs, errors are handled by automatically inserting the Unicode replacement character. In this case, ripgrep's output is guaranteed to be valid UTF-8 (excluding non-UTF-8 file paths, if they are printed). In all other cases, the source text is searched directly, which implies an assumption that it is at least ASCII compatible, but where UTF-8 is most useful. In this scenario, encoding errors are not detected. In this case, ripgrep's output will match the input exactly, byte-for-byte. This design may not be optimal in all cases, but it has some advantages: 1. In the happy path ("UTF-8 everywhere") remains happy. I have not been able to witness any performance regressions. 2. In the non-UTF-8 path, implementation complexity is kept relatively low. The cost here is transcoding itself. A potentially superior implementation might build decoding of any encoding into the regex engine itself. In particular, the fundamental problem with transcoding everything first is that literal optimizations are nearly negated. Future work should entail improving the user experience. For example, we might want to auto-detect more text encodings. A more elaborate UX experience might permit end users to specify multiple text encodings, although this seems hard to pull off in an ergonomic way. Fixes #1
Diffstat (limited to 'src/args.rs')
-rw-r--r--src/args.rs32
1 files changed, 32 insertions, 0 deletions
diff --git a/src/args.rs b/src/args.rs
index 8cf7cd69..7e60cd7d 100644
--- a/src/args.rs
+++ b/src/args.rs
@@ -10,6 +10,7 @@ use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use clap;
+use encoding_rs::Encoding;
use env_logger;
use grep::{Grep, GrepBuilder};
use log;
@@ -41,6 +42,7 @@ pub struct Args {
column: bool,
context_separator: Vec<u8>,
count: bool,
+ encoding: Option<&'static Encoding>,
files_with_matches: bool,
files_without_matches: bool,
eol: u8,
@@ -224,6 +226,7 @@ impl Args {
.after_context(self.after_context)
.before_context(self.before_context)
.count(self.count)
+ .encoding(self.encoding)
.files_with_matches(self.files_with_matches)
.files_without_matches(self.files_without_matches)
.eol(self.eol)
@@ -330,6 +333,7 @@ impl<'a> ArgMatches<'a> {
column: self.column(),
context_separator: self.context_separator(),
count: self.is_present("count"),
+ encoding: try!(self.encoding()),
files_with_matches: self.is_present("files-with-matches"),
files_without_matches: self.is_present("files-without-match"),
eol: b'\n',
@@ -569,6 +573,7 @@ impl<'a> ArgMatches<'a> {
/// will need to search.
fn mmap(&self, paths: &[PathBuf]) -> Result<bool> {
let (before, after) = try!(self.contexts());
+ let enc = try!(self.encoding());
Ok(if before > 0 || after > 0 || self.is_present("no-mmap") {
false
} else if self.is_present("mmap") {
@@ -576,6 +581,10 @@ impl<'a> ArgMatches<'a> {
} else if cfg!(target_os = "macos") {
// On Mac, memory maps appear to suck. Neat.
false
+ } else if enc.is_some() {
+ // There's no practical way to transcode a memory map that isn't
+ // isomorphic to searching over io::Read.
+ false
} else {
// If we're only searching a few paths and all of them are
// files, then memory maps are probably faster.
@@ -721,6 +730,29 @@ impl<'a> ArgMatches<'a> {
Ok(ColorSpecs::new(&specs))
}
+ /// Return the text encoding specified.
+ ///
+ /// If the label given by the caller doesn't correspond to a valid
+ /// supported encoding (and isn't `auto`), then return an error.
+ ///
+ /// A `None` encoding implies that the encoding should be automatically
+ /// detected on a per-file basis.
+ fn encoding(&self) -> Result<Option<&'static Encoding>> {
+ match self.0.value_of_lossy("encoding") {
+ None => Ok(None),
+ Some(label) => {
+ if label == "auto" {
+ return Ok(None);
+ }
+ match Encoding::for_label(label.as_bytes()) {
+ Some(enc) => Ok(Some(enc)),
+ None => Err(From::from(
+ format!("unsupported encoding: {}", label))),
+ }
+ }
+ }
+ }
+
/// Returns the approximate number of threads that ripgrep should use.
fn threads(&self) -> Result<usize> {
if self.is_present("sort-files") {