ansi_colours-1.0.1/.gitignore010060000017500001750000000000451335077614500144240ustar0000000000000000*.o /target /tools/target Cargo.lock ansi_colours-1.0.1/Cargo.toml.orig010060000017500001750000000012371335123755500153250ustar0000000000000000[package] name = "ansi_colours" description = "true-colour ↔ ANSI terminal palette converter" version = "1.0.1" readme = "README.md" authors = ["Michał Nazarewicz "] keywords = ["ansi", "terminal", "color", "rgb"] categories = ["command-line-interface"] license = "LGPL-3.0-or-later" repository = "https://github.com/mina86/ansi_colours" documentation = "https://docs.rs/ansi_colours" exclude = ["tools/**"] [badges] maintenance = { status = "actively-developed" } [dev-dependencies] delta_e = "^0.2" lab = "^0.4" [build-dependencies] cc = "^1.0" [profile.release] lto = true panic = 'abort' ansi_colours-1.0.1/Cargo.toml0000644000000022300000000000000115650ustar00# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g. crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] name = "ansi_colours" version = "1.0.1" authors = ["Michał Nazarewicz "] exclude = ["tools/**"] description = "true-colour ↔ ANSI terminal palette converter" documentation = "https://docs.rs/ansi_colours" readme = "README.md" keywords = ["ansi", "terminal", "color", "rgb"] categories = ["command-line-interface"] license = "LGPL-3.0-or-later" repository = "https://github.com/mina86/ansi_colours" [profile.release] lto = true panic = "abort" [dev-dependencies.delta_e] version = "^0.2" [dev-dependencies.lab] version = "^0.4" [build-dependencies.cc] version = "^1.0" [badges.maintenance] status = "actively-developed" ansi_colours-1.0.1/LICENSE010060000017500001750000000167441316364231200134440ustar0000000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. ansi_colours-1.0.1/README.md010060000017500001750000000044271335120121300136770ustar0000000000000000# True-colour ↔ ANSI terminal palette converter `ansi_colours` is a library which converts between 24-bit sRGB colours and 8-bit colour palette used by ANSI terminals such as xterm on rxvt-unicode in 256-colour mode. The most common use case is when using 24-bit colours in a terminal emulator which only support 8-bit colour palette. This package allows true-colours to be approximated by values supported by the terminal. When mapping true-colour into available 256-colour palette (of which only 240 are actually usable), this package tries to balance accuracy and performance. It doesn’t implement the fastest algorithm nor is it the most accurate, instead it uses a formula which should be fast enough and accurate enough for most use-cases. ## Usage This library has C, C++ and Rust bindings and can be easily used from any of those languages. ### Rust Using this package with Cargo projects is as simple as adding a single dependency: ```toml [dependencies] ansi_colours = "^1.0" ``` and then using one of the two functions that the library provides: ```rust extern crate ansi_colours; use ansi_colours::*; fn main() { // Colour at given index: println!("{:-3}: {:?}", 50, rgb_from_ansi256(50)); // Approximate true-colour by colour in the palette: let rgb = (100, 200, 150); let index = ansi256_from_rgb(rgb); println!("{:?} ~ {:-3} {:?}", rgb, index, rgb_from_ansi256(index)); } ``` ### C and C++ The easiest way to use this package in C or C++ is to copy the `ansi_colour.h` and `ansi256.c` files to your project (unfortunately, C nor C++ has any centralised package repository), set up compilation step for the `ansi256.c` file, add header file to include path and once all that is done use the two functions provided by this library can be used: ```c #include #include "ansi_colours.h" int main() { // Colour at given index: printf("%-3u #%06x\n", 50, rgb_from_ansi256(50)); // Approximate true-colour by colour in the palette: uint32_t rgb = 0x64C896; uint8_t index = ansi256_from_rgb(rgb); printf("#%06x ~ %-3u %06x\n", rgb, index, rgb_from_ansi256(index)); return 0; } ``` C nor C++ ecosystem has a centralised library distribution service which is why at this stage the easiest way is to just copy the two required files. ansi_colours-1.0.1/build.rs010060000017500001750000000001611335101346200140630ustar0000000000000000extern crate cc; fn main() { cc::Build::new() .file("src/ansi256.c") .compile("ansi256"); } ansi_colours-1.0.1/examples/convert.rs010060000017500001750000000012501335107103400162610ustar0000000000000000extern crate ansi_colours; use ansi_colours::*; fn main() { let args: Vec = std::env::args().collect(); if args.len() == 2 { let index = args[1].parse::().unwrap(); println!("{:-3}: {:?}", index, rgb_from_ansi256(index)); } else if args.len() == 4 { let rgb = (args[1].parse::().unwrap(), args[2].parse::().unwrap(), args[3].parse::().unwrap()); let index = ansi256_from_rgb(rgb); println!("{:?} ~ {:-3} {:?}", rgb, index, rgb_from_ansi256(index)); } else { eprintln!("usage: convert ( | )"); std::process::exit(1); } } ansi_colours-1.0.1/src/ansi256.c010060000017500001750000000175111335077550500145630ustar0000000000000000/* ansi_colours – true-colour ↔ ANSI terminal palette converter Copyright 2018 by Michał Nazarewicz ansi_colours is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. ansi_colours is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with ansi_colours. If not, see . */ #include #include #include "ansi_colours.h" static uint32_t cube_value(uint8_t r); static uint32_t cube_index_red(uint8_t r); static uint32_t cube_index_green(uint8_t g); static uint32_t cube_index_blue(uint8_t b); static uint8_t luminance(uint32_t rgb); static uint32_t distance(uint32_t x, uint32_t y); #define R(c) (((c) >> 16) & 0xff) #define G(c) (((c) >> 8) & 0xff) #define B(c) ( (c) & 0xff) /* Returns sRGB colour corresponding to the index in the 256-colour ANSI palette. */ uint32_t rgb_from_ansi256(uint8_t index) { /* The 16 system colours as used by default by xterm. Taken from XTerm-col.ad distributed with xterm source code. */ static uint32_t system_colours[16] = { 0x000000, 0xce0000, 0x00ce00, 0xcece00, 0x0000ee, 0xce00ce, 0x00cece, 0xefefef, 0x7f7f7f, 0xff0000, 0x00ff00, 0xffff00, 0x5c5cff, 0xff00ff, 0x00ffff, 0xffffff, }; if (!(index & 0xf0)) { /* equivalent to index < 16 */ return system_colours[index]; } else if (index < 232) { index -= 16; return ((cube_value(index / 36 ) << 16) | (cube_value(index / 6 % 6) << 8) | (cube_value(index % 6))); } else { index = (index - 232) * 10 + 8; return (uint32_t)index * 0x010101; } } /* Returns index of a colour in 256-colour ANSI palette approximating given sRGB colour. */ uint8_t ansi256_from_rgb(uint32_t rgb) { /* A lookup table for approximations of shades of grey. Values chosen to get smallest possible ΔE*₀₀. A lookup table is used because calculating correct mapping has several corner cases. For one, the greyscale ramp starts at rgb(8, 8, 8) but ends at rgb(238, 238, 238) resulting in asymmetric distance to the extreme values. For another, shades of grey are present in the greyscale ramp as well as the 6×6×6 colour cube making it necessary to consider multiple cases. */ static const uint8_t ansi256_from_grey[256] = { 16, 16, 16, 16, 16, 232, 232, 232, 232, 232, 232, 232, 232, 232, 233, 233, 233, 233, 233, 233, 233, 233, 233, 233, 234, 234, 234, 234, 234, 234, 234, 234, 234, 234, 235, 235, 235, 235, 235, 235, 235, 235, 235, 235, 236, 236, 236, 236, 236, 236, 236, 236, 236, 236, 237, 237, 237, 237, 237, 237, 237, 237, 237, 237, 238, 238, 238, 238, 238, 238, 238, 238, 238, 238, 239, 239, 239, 239, 239, 239, 239, 239, 239, 239, 240, 240, 240, 240, 240, 240, 240, 240, 59, 59, 59, 59, 59, 241, 241, 241, 241, 241, 241, 241, 242, 242, 242, 242, 242, 242, 242, 242, 242, 242, 243, 243, 243, 243, 243, 243, 243, 243, 243, 244, 244, 244, 244, 244, 244, 244, 244, 244, 102, 102, 102, 102, 102, 245, 245, 245, 245, 245, 245, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 247, 247, 247, 247, 247, 247, 247, 247, 247, 247, 248, 248, 248, 248, 248, 248, 248, 248, 248, 145, 145, 145, 145, 145, 249, 249, 249, 249, 249, 249, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 252, 252, 252, 252, 252, 252, 252, 252, 252, 188, 188, 188, 188, 188, 253, 253, 253, 253, 253, 253, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 231, 231, 231, 231, 231, 231, 231, 231, 231, }; /* First of, if it’s shade of grey, we know exactly the best colour that approximates it. */ if (R(rgb) == G(rgb) && G(rgb) == B(rgb)) { return ansi256_from_grey[rgb & 0xff]; } uint8_t grey_index = ansi256_from_grey[luminance(rgb)]; uint32_t grey_distance = distance(rgb, rgb_from_ansi256(grey_index)); uint32_t cube = cube_index_red(R(rgb)) + cube_index_green(G(rgb)) + cube_index_blue(B(rgb)); return distance(rgb, cube) < grey_distance ? cube >> 24 : grey_index; } /* The next three functions approximate a pure colour by a colour in the 6×6×6 colour cube. E.g. cube_index_red(r) approximates an rgb(r, 0, 0) colour. This was motivated by ΔE*₀₀ being most variable in dark colours so I felt it’s more important to better approximate dark colours than white colours. The return values of the functions is kinda weird but it makes ansi256_from_rgb a bit shorter, as in having to do a bit fewer things. */ #define CUBE_THRESHOLDS(a, b, c, d, e) \ if (v < a) return IDX(0, 0); \ else if (v < b) return IDX(1, 95); \ else if (v < c) return IDX(2, 135); \ else if (v < d) return IDX(3, 175); \ else if (v < e) return IDX(4, 215); \ else return IDX(5, 255); #define IDX(i, v) ((((uint32_t)i * 36 + 16) << 24) | ((uint32_t)v << 16)) static uint32_t cube_index_red(uint8_t v) { CUBE_THRESHOLDS(38, 115, 155, 196, 235); } #undef IDX #define IDX(i, v) ((((uint32_t)i * 6) << 24) | ((uint32_t)v << 8)) static uint32_t cube_index_green(uint8_t v) { CUBE_THRESHOLDS(36, 116, 154, 195, 235); } #undef IDX #define IDX(i, v) (((uint32_t)i << 24) | (uint32_t)v) static uint32_t cube_index_blue(uint8_t v) { CUBE_THRESHOLDS(35, 115, 155, 195, 235); } #undef IDX #undef CUBE_THRESHOLDS /* Translates an index in the 6×6×6 colour cube to a value in sRGB space. The argument must be less than six. */ static uint32_t cube_value(uint8_t idx) { static const uint8_t values[] = {0, 95, 135, 175, 215, 255}; return values[idx]; } /* Returns luminance of given sRGB colour. The calculation favours speed over precision and so doesn’t correctly account for sRGB’s gamma correction. */ static uint8_t luminance(uint32_t rgb) { /* The following weighted average is as fast as naive arithmetic mean and at the same time noticeably more prices. The coefficients are the second row of the RGB->XYZ conversion matrix (i.e. values for calculating Y from linear RGB) which I’ve calculated so that denominator is 2^²⁴ to simplify division. */ return ((uint32_t) 3568058 * R(rgb) + (uint32_t)11998262 * G(rgb) + (uint32_t) 1210896 * B(rgb)) >> 24; /* Approximating sRGB gamma correction with a simple γ=2 improves the precision considerably but is also five times slower than the above (and probably slower still on architectures lacking MMS or FPU). return sqrtf((float)r * (float)r * 0.2126729f + (float)g * (float)g * 0.7151521f + (float)b * (float)b * 0.0721750); Doing proper gamma correction results in further improvement but is also 20 times slower, so we’re opting out from doing that. */ } /* Calculates distance between two colours. Tries to balance speed and perceptual correctness. It’s not a proper metric but two properties this function provides are: d(x, x) = 0 and d(x, y) < d(x, z) implies x being closer to y than to z. */ static uint32_t distance(uint32_t x, uint32_t y) { /* See though we’re doing a few things to avoid some of the calculations. We can do that since we only care about some properties of the metric. */ int32_t r_sum = R(x) + R(y); int32_t r = (int32_t)R(x) - (int32_t)R(y); int32_t g = (int32_t)G(x) - (int32_t)G(y); int32_t b = (int32_t)B(x) - (int32_t)B(y); return (1024 + r_sum) * r * r + 2048 * g * g + (1534 - r_sum) * b * b; } ansi_colours-1.0.1/src/ansi_colours.h010060000017500001750000000046151335077524400161020ustar0000000000000000/* ansi_colours – true-colour ↔ ANSI terminal palette converter Copyright 2018 by Michał Nazarewicz ansi_colours is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. ansi_colours is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with ansi_colours. If not, see . */ #include #ifdef __cplusplus extern "C" { #endif /* Returns sRGB colour corresponding to the index in the 256-colour ANSI * palette. The colour is returned as 24-bit 0xrrggbb number. * * The first 16 colours (so-called system colours) are not standardised and * terminal emulators often allow them to be customised. Because of this, their * value should not be relied upon. For system colours, this function returns * default colours used by XTerm. * * Remaining 240 colours consist of a 6×6×6 colour cube and a 24-step greyscale * ramp. Those are standardised and thus should be the same on every terminal * which supports 256-colour colour palette. * * For example: * * assert(0x000000 == rgb_from_ansi256( 16)); * assert(0x5f87af == rgb_from_ansi256( 67)); * assert(0xffffff == rgb_from_ansi256(231)); * assert(0xeeeeee == rgb_from_ansi256(255)); */ uint32_t rgb_from_ansi256(uint8_t index); /* Returns index of a colour in 256-colour ANSI palette approximating given sRGB * colour. The sRGB colour is expected in 24-bit 0xrrggbb format. (Most * significant eight bits of the argument are ignored). * * Because the first 16 colours of the palette are not standardised and usually * user-configurable, the function essentially ignores them. * * For example: * * assert( 16 == ansi256_from_rgb(0x000000)); * assert( 16 == ansi256_from_rgb(0x010101)); * assert( 16 == ansi256_from_rgb(0x000102)); * assert( 67 == ansi256_from_rgb(0x5f87af)); * assert(231 == ansi256_from_rgb(0xffffff)); */ uint8_t ansi256_from_rgb(uint32_t rgb); #ifdef __cplusplus } #endif ansi_colours-1.0.1/src/externs.rs010060000017500001750000000016061335077361500152640ustar0000000000000000// ansi_colours – true-colour ↔ ANSI terminal palette converter // Copyright 2018 by Michał Nazarewicz // // ansi_colours is free software: you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation; either version 3 of the License, or (at // your option) any later version. // // ansi_colours is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser // General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with ansi_colours. If not, see . extern { pub fn rgb_from_ansi256(index: u8) -> u32; pub fn ansi256_from_rgb(rgb: u32) -> u8; } ansi_colours-1.0.1/src/lib.rs010060000017500001750000000117401335123755500143410ustar0000000000000000// ansi_colours – true-colour ↔ ANSI terminal palette converter // Copyright 2018 by Michał Nazarewicz // // ansi_colours is free software: you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation; either version 3 of the License, or (at // your option) any later version. // // ansi_colours is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser // General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with ansi_colours. If not, see . //! `ansi_colours` is a library which converts between 24-bit sRGB colours and //! 8-bit colour palette used by ANSI terminals such as xterm on rxvt-unicode in //! 256-colour mode. //! //! The most common use case is when using 24-bit colours in a terminal emulator //! which only support 8-bit colour palette. This package allows true-colours //! to be approximated by values supported by the terminal. //! //! When mapping true-colour into available 256-colour palette (of which only //! 240 are actually usable), this package tries to balance accuracy and //! performance. It doesn’t implement the fastest algorithm nor is it the most //! accurate, instead it uses a formula which should be fast enough and accurate //! enough for most use-cases. //! //! ## Usage //! //! Using this library with Cargo projects is as simple as adding a single //! dependency: //! //! ```toml //! [dependencies] //! ansi_colours = "^1.0" //! ``` //! //! and then using one of the two functions that the library provides: //! //! ```rust //! extern crate ansi_colours; //! //! use ansi_colours::*; //! //! fn main() { //! // Colour at given index: //! println!("{:-3}: {:?}", 50, rgb_from_ansi256(50)); //! //! // Approximate true-colour by colour in the palette: //! let rgb = (100, 200, 150); //! let index = ansi256_from_rgb(rgb); //! println!("{:?} ~ {:-3} {:?}", rgb, index, rgb_from_ansi256(index)); //! } //! ``` mod externs; /// Returns sRGB colour corresponding to the index in the 256-colour ANSI /// palette. /// /// The first 16 colours (so-called system colours) are not standardised and /// terminal emulators often allow them to be customised. Because of this, /// their value should not be relied upon. For system colours, this function /// returns default colours used by XTerm. /// /// Remaining 240 colours consist of a 6×6×6 colour cube and a 24-step greyscale /// ramp. Those are standardised and thus should be the same on every terminal /// which supports 256-colour colour palette. /// /// # Examples /// /// /// ``` /// assert_eq!(( 0, 0, 0), ansi_colours::rgb_from_ansi256( 16)); /// assert_eq!(( 95, 135, 175), ansi_colours::rgb_from_ansi256( 67)); /// assert_eq!((255, 255, 255), ansi_colours::rgb_from_ansi256(231)); /// assert_eq!((238, 238, 238), ansi_colours::rgb_from_ansi256(255)); /// ``` #[inline] pub fn rgb_from_ansi256(idx: u8) -> (u8, u8, u8) { let rgb = unsafe { externs::rgb_from_ansi256(idx) }; ((rgb >> 16) as u8, (rgb >> 8) as u8, rgb as u8) } /// Returns index of a colour in 256-colour ANSI palette approximating given /// sRGB colour. /// /// Because the first 16 colours of the palette are not standardised and usually /// user-configurable, the function essentially ignores them. /// /// Th first argument uses `AsRGB` trait so that the function can be called in /// multiple ways using different representations of RGB colours such as /// `0xRRGGBB` integer, `(r, g, b)` tuple or `[r, g, b]` array. /// /// # Examples /// /// /// ``` /// assert_eq!( 16, ansi_colours::ansi256_from_rgb(0x000000)); /// assert_eq!( 16, ansi_colours::ansi256_from_rgb( ( 1, 1, 1))); /// assert_eq!( 16, ansi_colours::ansi256_from_rgb( [ 0, 1, 2])); /// assert_eq!( 67, ansi_colours::ansi256_from_rgb(&( 95, 135, 175))); /// assert_eq!(231, ansi_colours::ansi256_from_rgb(&[255, 255, 255])); /// ``` #[inline] pub fn ansi256_from_rgb(rgb: C) -> u8 { unsafe { externs::ansi256_from_rgb(rgb.as_u32()) } } /// A trait for types which (can) represent an sRGB colour. Used to provide /// overloaded versions of `ansi256_from_rgb` function. pub trait AsRGB { /// Returns representation of the sRGB colour as a 24-bit `0xRRGGBB` /// integer. fn as_u32(&self) -> u32; } /// Representation of an RGB colour as 24-bit `0xRRGGBB` integer. impl AsRGB for u32 { fn as_u32(&self) -> u32 { *self } } #[inline] fn to_u32(r: u8, g: u8, b: u8) -> u32 { ((r as u32) << 16) | ((g as u32) << 8) | (b as u32) } impl AsRGB for (u8, u8, u8) { fn as_u32(&self) -> u32 { to_u32(self.0, self.1, self.2) } } impl AsRGB for [u8; 3] { fn as_u32(&self) -> u32 { to_u32(self[0], self[1], self[2]) } } impl<'a, T: AsRGB + ?Sized> AsRGB for &'a T { fn as_u32(&self) -> u32 { (*self).as_u32() } } ansi_colours-1.0.1/tests/ansi256.rs010060000017500001750000000044261335077512700153410ustar0000000000000000extern crate delta_e; extern crate lab; extern crate ansi_colours; fn to_rgb(index: u8) -> (u8, u8, u8) { ansi_colours::rgb_from_ansi256(index) } fn to_ansi(rgb: (u8, u8, u8)) -> u8 { ansi_colours::ansi256_from_rgb(rgb) } #[test] fn test_to_rgb() { static SYSTEM_COLOURS: [(u8, u8, u8); 16] = [ (0x00, 0x00, 0x00), (0xce, 0x00, 0x00), (0x00, 0xce, 0x00), (0xce, 0xce, 0x00), (0x00, 0x00, 0xee), (0xce, 0x00, 0xce), (0x00, 0xce, 0xce), (0xef, 0xef, 0xef), (0x7f, 0x7f, 0x7f), (0xff, 0x00, 0x00), (0x00, 0xff, 0x00), (0xff, 0xff, 0x00), (0x5c, 0x5c, 0xff), (0xff, 0x00, 0xff), (0x00, 0xff, 0xff), (0xff, 0xff, 0xff), ]; static CUBE_VALUES: [u8; 6] = [0, 95, 135, 175, 215, 255]; // System colours for (idx, rgb) in SYSTEM_COLOURS.iter().enumerate() { assert_eq!(*rgb, to_rgb(idx as u8)); } // Colour cube for idx in 0..216 { assert_eq!((CUBE_VALUES[ idx / 36 ], CUBE_VALUES[(idx / 6) % 6], CUBE_VALUES[ idx % 6]), to_rgb(16 + idx as u8)); } // Greyscale ramp for idx in 0..24 { let y = idx * 10 + 8; assert_eq!((y, y, y), to_rgb(idx + 232)); } } /// Tries all colours in the 256-colour ANSI palette and chooses one with /// smallest ΔE*₀₀ to `rgb(y, y, y)`. fn best_grey(y: u8) -> u8 { let mut best_dist = std::f32::INFINITY; let mut best_idx = 0; let grey = [y, y, y]; for idx in 16..256 { let (r, g, b) = to_rgb(idx as u8); let dist = delta_e::DE2000::from_rgb(&grey, &[r, g, b]); if dist < best_dist { best_dist = dist; best_idx = idx as u8; } } best_idx } #[test] fn test_from_rgb_grey() { for i in 0..256 { assert_eq!(best_grey(i as u8), to_ansi((i as u8, i as u8, i as u8))); } } #[test] fn test_to_ansi_exact() { for i in 16..256 { let rgb = to_rgb(i as u8); let got = to_ansi(rgb); assert_eq!(i as u8, got, "want {:?} but got {:?}", rgb, to_rgb(got)); } } #[test] fn test_to_ansi_approx() { assert_eq!( 16, to_ansi(( 1, 1, 1))); assert_eq!(232, to_ansi(( 7, 7, 7))); assert_eq!(232, to_ansi(( 8, 7, 8))); assert_eq!( 64, to_ansi(( 97, 134, 8))); }