File: WideString.hs

package info (click to toggle)
haskell-hledger-lib 1.50.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,520 kB
  • sloc: haskell: 16,495; makefile: 7
file content (39 lines) | stat: -rw-r--r-- 1,102 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
-- | Calculate the width of String and Text, being aware of wide characters.

module Text.WideString (
  -- * Text Builders which keep track of length
  WideBuilder(..),
  wbUnpack,
  wbToText,
  wbFromText
  ) where

import Data.Text (Text)
import Data.Text.Lazy qualified as TL
import Data.Text.Lazy.Builder qualified as TB
import Text.DocLayout (realLength)


-- | Helper for constructing Builders while keeping track of text width.
data WideBuilder = WideBuilder
  { wbBuilder :: !TB.Builder
  , wbWidth   :: !Int
  } deriving (Show)

instance Semigroup WideBuilder where
  WideBuilder x i <> WideBuilder y j = WideBuilder (x <> y) (i + j)

instance Monoid WideBuilder where
  mempty = WideBuilder mempty 0

-- | Convert a WideBuilder to a strict Text.
wbToText :: WideBuilder -> Text
wbToText = TL.toStrict . TB.toLazyText . wbBuilder

-- | Convert a strict Text to a WideBuilder.
wbFromText :: Text -> WideBuilder
wbFromText t = WideBuilder (TB.fromText t) (realLength t)

-- | Convert a WideBuilder to a String.
wbUnpack :: WideBuilder -> String
wbUnpack = TL.unpack . TB.toLazyText . wbBuilder