]> gitweb.factorcode.org Git - factor.git/blobdiff - extra/io/streams/256color/256color.factor
io.streams.256color: faster by caching styles
[factor.git] / extra / io / streams / 256color / 256color.factor
index 58bdc5a31c907fc0ea564c4b456068a4b7f34d88..6bce05a25d1ee31fc23d3984ab8a6924b496008b 100644 (file)
@@ -2,9 +2,9 @@
 ! See http://factorcode.org/license.txt for BSD license
 
 USING: accessors arrays assocs destructors environment
-formatting fry io io.streams.string io.styles kernel locals
-math math.functions math.ranges math.vectors namespaces
-sequences sequences.extras strings strings.tables ;
+formatting io io.streams.escape-codes io.streams.string
+io.styles kernel math math.functions math.vectors namespaces
+ranges sequences strings strings.tables ;
 
 IN: io.streams.256color
 
@@ -60,27 +60,23 @@ intensities [| r i |
     color>rgb '[ _ distance ]
     256colors [ keys swap infimum-by ] [ at ] bi ;
 
-: color>foreground ( color -- str )
+MEMO: color>foreground ( color -- string )
     color>256color "\e[38;5;%sm" sprintf ;
 
-: color>background ( color -- str )
+MEMO: color>background ( color -- string )
     color>256color "\e[48;5;%sm" sprintf ;
 
-TUPLE: 256color stream ;
+TUPLE: 256color < filter-writer ;
 
 C: <256color> 256color
 
-M: 256color stream-write1 stream>> stream-write1 ;
-M: 256color stream-write stream>> stream-write ;
-M: 256color stream-flush stream>> stream-flush ;
-M: 256color stream-nl stream>> stream-nl ;
-
-M: 256color stream-format
-    [
-        [ foreground swap at [ color>foreground ] [ "" ] if* ]
-        [ background swap at [ color>background ] [ "" ] if* ]
-        bi append [ "\e[0m" surround ] unless-empty
-    ] dip stream>> stream-write ;
+M:: 256color stream-format ( str style stream -- )
+    stream stream>> :> out
+    style foreground of [ color>foreground out stream-write t ] [ f ] if*
+    style background of [ color>background out stream-write t ] [ f ] if*
+    style font-style of [ font-styles out stream-write t ] [ f ] if*
+    or or [ "\e[0m" out stream-write ] unless
+    str out stream-write ;
 
 M: 256color make-span-stream
     swap <style-stream> <ignore-close-stream> ;