diff --git a/src/FSharpPlus/Collection.fs b/src/FSharpPlus/Collection.fs index d1bbb36ed..4555578e2 100644 --- a/src/FSharpPlus/Collection.fs +++ b/src/FSharpPlus/Collection.fs @@ -34,7 +34,7 @@ type OfSeq = static member inline OfSeq (x: seq<'t> , _: 'UserType , _: OfSeq ) = (^UserType : (static member OfSeq : seq<'t> -> ^UserType) x) static member OfSeq (x , _: 't [] , _: OfSeq ) = Array.ofSeq<'t> x static member OfSeq (x , _: 't list , _: OfSeq ) = List.ofSeq<'t> x - static member OfSeq (x: seq , _: string , _: OfSeq ) = String.Join ("", Array.ofSeq x) + static member OfSeq (x: seq , _: string , _: OfSeq ) = String.ofSeq x static member OfSeq (x: seq , _: Text.StringBuilder , _: OfSeq ) = (StringBuilder (), x) ||> Seq.fold (fun x -> x.Append) static member OfSeq (x: seq<'t> , _: Stack<'t> , _: OfSeq ) = Generic.Stack x @@ -68,7 +68,7 @@ type OfList = static member inline OfList (x: list<'t> , _: 'UserType , _: OfList ) = (^UserType : (static member OfList : list<'t> -> ^UserType) x) static member OfList (x , _: 't [] , _: OfList ) = Array.ofList<'t> x static member OfList (x , _: 't list , _: OfList ) = x - static member OfList (x: list , _: string , _: OfList ) = String.Join ("", Array.ofList x) + static member OfList (x: list , _: string , _: OfList ) = String.ofList x static member OfList (x: list , _: Text.StringBuilder , _: OfList ) = (StringBuilder (), x) ||> List.fold (fun x -> x.Append) static member OfList (x: list<'t> , _: Stack<'t> , _: OfList ) = Generic.Stack x @@ -104,7 +104,7 @@ type Filter with type Skip = inherit Default1 static member inline Skip (x: '``Foldable<'T>``, n, []_impl: Default1) = x |> ToSeq.Invoke |> Seq.skip n |> OfSeq.Invoke : '``Foldable<'T>`` - static member Skip (x: string , n, []_impl: Skip ) = x.[n..] + static member Skip (x: string , n, []_impl: Skip ) = String.skip n x static member Skip (x: StringBuilder , n, []_impl: Skip ) = new StringBuilder(x.ToString().[n..]) static member Skip (x: 'a [] , n, []_impl: Skip ) = x.[n..] : 'a [] static member Skip (x: 'a ResizeArray , n, []_impl: Skip ) = ResizeArray<'a> (Seq.skip n x) @@ -120,7 +120,7 @@ type Skip = type Take = inherit Default1 static member inline Take (x: '``Foldable<'T>``, n, []_impl: Default1) = x |> ToSeq.Invoke |> Seq.take n |> OfSeq.Invoke : '``Foldable<'T>`` - static member Take (x: string , n, []_impl: Take ) = x.[..n-1] + static member Take (x: string , n, []_impl: Take ) = String.take n x static member Take (x: StringBuilder , n, []_impl: Take ) = new StringBuilder(x.ToString().[..n-1]) static member Take (x: 'a [] , n, []_impl: Take ) = x.[..n-1] : 'a [] static member Take (x: 'a ResizeArray , n, []_impl: Take ) = ResizeArray<'a> (Seq.take n x) @@ -135,6 +135,7 @@ type Take = type TakeWhile = inherit Default1 static member inline TakeWhile (x: '``Foldable<'T>``, p, []_impl: Default1 ) = x |> ToSeq.Invoke |> Seq.takeWhile p |> OfSeq.Invoke : '``Foldable<'T>`` + static member TakeWhile (x: string , p, []_impl: TakeWhile) = String.takeWhile p x static member TakeWhile (x: 'a [] , p, []_impl: TakeWhile) = Array.takeWhile p x static member TakeWhile (x: 'a ResizeArray , p, []_impl: TakeWhile) = ResizeArray<'a> (Seq.takeWhile p x) static member TakeWhile (x: list<'a> , p, []_impl: TakeWhile) = List.takeWhile p x @@ -148,6 +149,7 @@ type TakeWhile = type SkipWhile = inherit Default1 static member inline SkipWhile (x: '``Foldable<'T>``, p, []_impl: Default1 ) = x |> ToSeq.Invoke |> Seq.skipWhile p |> OfSeq.Invoke : '``Foldable<'T>`` + static member SkipWhile (x: string , p, []_impl: SkipWhile) = String.skipWhile p x static member SkipWhile (x: 'a [] , p, []_impl: SkipWhile) = Array.skipWhile p x static member SkipWhile (x: 'a ResizeArray , p, []_impl: SkipWhile) = ResizeArray<'a> (Seq.skipWhile p x) static member SkipWhile (x: list<'a> , p, []_impl: SkipWhile) = List.skipWhile p x @@ -161,7 +163,7 @@ type SkipWhile = type Drop = inherit Default1 static member inline Drop (x: '``Foldable<'T>``, n, []_impl: Default1) = x |> ToSeq.Invoke |> Seq.drop n |> OfSeq.Invoke : '``Foldable<'T>`` - static member Drop (x: string , n, []_impl: Drop ) = if n > 0 then (if x.Length > n then x.[n..] else "") else x + static member Drop (x: string , n, []_impl: Drop ) = String.drop n x static member Drop (x: StringBuilder , n, []_impl: Drop ) = if n > 0 then (if x.Length > n then new StringBuilder(x.ToString().[n..]) else new StringBuilder ()) else new StringBuilder (string x) static member Drop (x: 'a [] , n, []_impl: Drop ) = if n > 0 then (if x.Length > n then x.[n..] else [||]) else x : 'a [] static member Drop (x: 'a ResizeArray , n, []_impl: Drop ) = ResizeArray<'a> (Seq.drop n x) @@ -177,7 +179,7 @@ type Drop = type Limit = inherit Default1 static member inline Limit (x: '``Foldable<'T>``, n, []_impl: Default1) = x |> ToSeq.Invoke |> Seq.truncate n |> OfSeq.Invoke : '``Foldable<'T>`` - static member Limit (x: string , n, []_impl: Limit ) = if n < 1 then "" elif n < x.Length then x.[..n-1] else x + static member Limit (x: string , n, []_impl: Limit ) = String.truncate n x static member Limit (x: StringBuilder , n, []_impl: Limit ) = new StringBuilder(x.ToString().[..n-1]) static member Limit (x: 'a [] , n, []_impl: Limit ) = if n < 1 then [||] elif n < x.Length then x.[..n-1] else x : 'a [] static member Limit (x: 'a ResizeArray , n, []_impl: Limit ) = ResizeArray<'a> (Seq.truncate n x) @@ -410,4 +412,4 @@ type Intercalate = static member inline Invoke (sep: 'Monoid) (source: '``Foldable<'Monoid>``) = let inline call_2 (a: ^a, b: ^b, s: ^c) = ((^a or ^c) : (static member Intercalate : _*_*_ -> _) b, s, a) let inline call (a: 'a, b: 'b, s) = call_2 (a, b, s) - call (Unchecked.defaultof, source, sep) : 'Monoid \ No newline at end of file + call (Unchecked.defaultof, source, sep) : 'Monoid diff --git a/src/FSharpPlus/Extensions.fs b/src/FSharpPlus/Extensions.fs index 9c9ff4a2a..8afa67b19 100644 --- a/src/FSharpPlus/Extensions.fs +++ b/src/FSharpPlus/Extensions.fs @@ -295,6 +295,103 @@ module String = |> String.filter (fun ch -> CharUnicodeInfo.GetUnicodeCategory ch <> UnicodeCategory.NonSpacingMark) |> normalize NormalizationForm.FormC + /// Pads the beginning of the given string with spaces so that it has a specified total length. + let padLeft totalLength (source: string) = source.PadLeft totalLength + /// Pads the beginning of the given string with a specified character so that it has a specified total length. + let padLeftWith totalLength paddingChar (source: string) = source.PadLeft (totalLength, paddingChar) + /// Pads the end of the given string with spaces so that it has a specified total length. + let padRight totalLength (source: string) = source.PadRight totalLength + /// Pads the end of the given string with a specified character so that it has a specified total length. + let padRightWith totalLength paddingChar (source: string) = source.PadRight (totalLength, paddingChar) + + /// Removes all leading and trailing occurrences of specified characters from the given string. + let trim (trimChars: char seq) (source: string) = source.Trim (Seq.toArray trimChars) + /// Removes all leading occurrences of specified characters from the given string. + let trimStart (trimChars: char seq) (source: string) = source.TrimStart (Seq.toArray trimChars) + /// Removes all trailing occurrences of specified characters from the given string. + let trimEnd (trimChars: char seq) (source: string) = source.TrimEnd (Seq.toArray trimChars) + + let toArray (source: string) = source.ToCharArray () + let ofArray (source: char []) = new String (source) + let toList (source: string) = toArray source |> List.ofArray + let ofList (source: char list) = new String (source |> Array.ofList) + let toSeq (source: string) = source :> seq + let ofSeq (source: seq) = String.Join (String.Empty, source) + + let item (index: int) (source: string) = source.[index] + let tryItem (index: int) (source: string) = if index >= 0 && index < source.Length then Some source.[index] else None + + let rev (source: string) = new String (source.ToCharArray () |> Array.rev) + + let take count (source: string) = source.[..count-1] + let skip count (source: string) = source.[count..] + let takeWhile (predicate: char -> bool) (source: string) = + if String.IsNullOrEmpty source then + String.Empty + else + let mutable i = 0 + let length = String.length source + while i < length && predicate source.[i] do + i <- i + 1 + if i = 0 then "" + else source |> take i + let skipWhile (predicate: char -> bool) (source: string) = + if String.IsNullOrEmpty source then + String.Empty + else + let mutable i = 0 + let length = String.length source + while i < length && predicate source.[i] do + i <- i + 1 + if i = 0 then "" + else source |> skip i + /// Returns a string that have at most N characters from the beginning of the original string. + /// It returns the original string if it is shorter than count. + let truncate count (source: string) = + if count < 1 then String.Empty + else if String.length source <= count then source + else take count source + /// Returns a string that drops first N characters of the original string. + /// When count exceeds the length of the string it returns an empty string. + let drop count (source: string) = + if count < 1 then source + else if String.length source >= count then String.Empty + else skip count source + + let findIndex (char: char) (source: string) = + let index = source.IndexOf char + if index = -1 then + ArgumentException("An index satisfying the predicate was not found in the string.") |> raise + else + index + let tryFindIndex (char: char) (source: string) = + let index = source.IndexOf char + if index = -1 then None else Some index + + let findSliceIndex (slice: string) (source: string) = + let index = source.IndexOf slice + if index = -1 then + ArgumentException("An index satisfying the predicate was not found in the string.") |> raise + else + index + let tryFindSliceIndex (slice: string) (source: string) = + let index = source.IndexOf slice + if index = -1 then None else Some index + + /// Converts the string to an array of Int32 code-points (the actual Unicode Code Point number). + let toCodePoints (source : string) : seq = + let mapper i c = + // Ignore the low-surrogate because it's already been converted + if c |> Char.IsLowSurrogate then None + else Char.ConvertToUtf32 (source, i) |> Some + source |> Seq.mapi mapper |> Seq.choose id + /// Converts the array of Int32 code-points (the actual Unicode Code Point number) to a string. + let ofCodePoints (source: seq) : string = + source |> Seq.map Char.ConvertFromUtf32 |> String.concat String.Empty + + /// Converts a string to a byte-array using the specified encoding. + let getBytes (encoding: System.Text.Encoding) (source: string) : byte [] = encoding.GetBytes source + /// Additional operations on IReadOnlyCollection<'T> [] diff --git a/src/FSharpPlus/Foldable.fs b/src/FSharpPlus/Foldable.fs index 9e212a83b..cb9e5e999 100644 --- a/src/FSharpPlus/Foldable.fs +++ b/src/FSharpPlus/Foldable.fs @@ -42,7 +42,7 @@ type ToSeq = inherit Default1 static member ToSeq (x: seq<'T> , []_impl: ToSeq) = x static member ToSeq (x: Text.StringBuilder, _: ToSeq) = string x :> seq - static member ToSeq (x: string , _: ToSeq) = x :> seq + static member ToSeq (x: string , _: ToSeq) = String.toSeq x static member ToSeq (x: option<'T>, []_impl: ToSeq) = match x with Some x -> Seq.singleton x | _ -> Seq.empty static member ToSeq (x: Id<'T> , []_impl: ToSeq) = Seq.singleton x.getValue @@ -65,7 +65,7 @@ type ToList = static member ToList (x: seq<'a> , []_impl: Default2) = Seq.toList x static member inline ToList (x , []_impl: Default1) = (^Foldable : (static member ToList : 'Foldable->list<_>) x) static member ToList (x: Set<'a> , []_impl: ToList ) = Set.toList x - static member ToList (x: string , []_impl: ToList ) = x.ToCharArray () |> Array.toList + static member ToList (x: string , []_impl: ToList ) = String.toList x static member ToList (x: StringBuilder , []_impl: ToList ) = x.ToString().ToCharArray() |> Array.toList static member ToList (x: 'a [] , []_impl: ToList ) = Array.toList x static member ToList (x: 'a ResizeArray, []_impl: ToList ) = Seq.toList x @@ -83,7 +83,7 @@ type ToArray = static member ToArray (x: seq<'a> , []_impl: Default2) = Seq.toArray x static member inline ToArray (x , []_impl: Default1) = (^Foldable : (static member ToArray : 'Foldable->array<_>) x) static member ToArray (x: Set<'a> , []_impl: ToArray ) = Set.toArray x - static member ToArray (x: string , []_impl: ToArray ) = x.ToCharArray () + static member ToArray (x: string , []_impl: ToArray ) = String.toArray x static member ToArray (x: StringBuilder , []_impl: ToArray ) = x.ToString().ToCharArray () static member ToArray (x: 'a [] , []_impl: ToArray ) = x static member ToArray (x: 'a ResizeArray, []_impl: ToArray ) = Seq.toArray x @@ -375,4 +375,4 @@ type Length = static member inline Invoke (source: '``Foldable<'T>``) = let inline call_2 (a: ^a, b: ^b) = ((^a or ^b) : (static member Length : _*_ -> _) b, a) let inline call (a: 'a, b: 'b) = call_2 (a, b) - call (Unchecked.defaultof, source) : int \ No newline at end of file + call (Unchecked.defaultof, source) : int diff --git a/src/FSharpPlus/Indexable.fs b/src/FSharpPlus/Indexable.fs index 18cc79506..431b4436a 100644 --- a/src/FSharpPlus/Indexable.fs +++ b/src/FSharpPlus/Indexable.fs @@ -5,6 +5,7 @@ open System.Runtime.CompilerServices open System.Runtime.InteropServices open System.Text open System.Collections.Generic +open FSharpPlus open FSharpPlus.Internals open FSharpPlus.Internals.Prelude @@ -16,7 +17,7 @@ type Item = inherit Default1 static member inline Item (x: '``Indexable<'T>`` , k , []_impl: Default1) = (^``Indexable<'T>`` : (member get_Item : _ -> 'T) x, k) : 'T static member inline Item (_: 'T when 'T: null and 'T: struct, _, _impl: Default1) = () - static member Item (x: string , n , []_impl: Item ) = x.[n] + static member Item (x: string , n , []_impl: Item ) = String.item n x static member Item (x: StringBuilder , n , []_impl: Item ) = x.ToString().[n] static member Item (x: 'T [] , n , []_impl: Item ) = x.[n] : 'T static member Item (x: 'T [,] , (i,j) , []_impl: Item ) = x.[i,j] : 'T @@ -36,7 +37,7 @@ type TryItem = if (^``Indexable<'T>``: (member TryGetValue: _ * _ -> _) (x, k, &r)) then Some r else None static member inline TryItem (x: '``Indexable<'T>``, k , []_impl: Default1) = (^``Indexable<'T>`` : (static member TryItem : _ * _ -> _) k, x) : 'T option static member inline TryItem (_: 'T when 'T: null and 'T: struct, _ , _impl: Default1) = () - static member TryItem (x: string , n , []_impl: TryItem ) = if n >= 0 && n < x.Length then Some (x.[n]) else None + static member TryItem (x: string , n , []_impl: TryItem ) = String.tryItem n x static member TryItem (x: StringBuilder , n , []_impl: TryItem ) = if n >= 0 && n < x.Length then Some ((string x).[n]) else None static member TryItem (x: 'a [] , n , []_impl: TryItem ) = if n >= x.GetLowerBound 0 && n <= x.GetUpperBound 0 then Some x.[n] else None : 'a option static member TryItem (x: 'a [,] , (i,j) , []_impl: TryItem ) = if (i, j) >= (x.GetLowerBound 0, x.GetLowerBound 1 ) && (i, j) <= (x.GetUpperBound 0, x.GetUpperBound 1 ) then Some x.[i,j] else None : 'a option @@ -103,4 +104,4 @@ type TraverseIndexed = static member inline Invoke f t = let inline call_3 (a: ^a, b: ^b, c: ^c, f) = ((^a or ^b or ^c) : (static member TraverseIndexed : _*_*_*_ -> _) b, f, c, a) let inline call (a: 'a, b: 'b, f) = call_3 (a, b, Unchecked.defaultof<'r>, f) : 'r - call (Unchecked.defaultof, t, f) \ No newline at end of file + call (Unchecked.defaultof, t, f) diff --git a/tests/FSharpPlus.Tests/Extensions.fs b/tests/FSharpPlus.Tests/Extensions.fs index 394608180..71d84b1be 100644 --- a/tests/FSharpPlus.Tests/Extensions.fs +++ b/tests/FSharpPlus.Tests/Extensions.fs @@ -230,4 +230,36 @@ let ``IReadOnlyDictionary.union provides same end result as Dict.unionWith picki let r1 = m1 |> IReadOnlyDictionary.union m2 |> Seq.toList let r2 = m1 |> IReadOnlyDictionary.unionWith konst m2 |> Seq.toList - areEqual r1 r2 \ No newline at end of file + areEqual r1 r2 + +[] +let ``String.toCodePoints >> String.ofCodePoints should preserve the original string`` () = + // some naughty strings adopted from https://github.com/minimaxir/big-list-of-naughty-strings + // The MIT License (MIT), Copyright (c) 2015 Max Woolf + let testStrings = [ + "田中さんにあげて下さい" + "パーティーへ行かないか" + "和製漢語" + "部落格" + "사회과학원 어학연구소" + "찦차를 타고 온 펲시맨과 쑛다리 똠방각하" + "社會科學院語學研究所" + "울란바토르" + "𠜎𠜱𠝹𠱓𠱸𠲖𠳏" + "ヽ༼ຈل͜ຈ༽ノ ヽ༼ຈل͜ຈ༽ノ" + "(。◕ ∀ ◕。)" + "`ィ(´∀`∩" + "__ロ(_*)" + "・( ̄∀ ̄)・:*:" + "゚・✿ヾ╲(。◕‿◕。)╱✿・゚" + "表ポあA鷗ŒéB逍Üߪąñ丂㐀𠀀" + "0️⃣ 1️⃣ 2️⃣ 3️⃣ 4️⃣ 5️⃣ 6️⃣ 7️⃣ 8️⃣ 9️⃣ 🔟" + "🇺🇸🇷🇺🇸 🇦🇫🇦🇲🇸" + "🇺🇸🇷🇺🇸🇦🇫🇦🇲" + "🇺🇸🇷🇺🇸🇦" + "If you're reading this, you've been in a coma for almost 20 years now. We're trying a new technique. We don't know where this message will end up in your dream, but we hope it works. Please wake up, we miss you." + ] + + for s in testStrings do + areEqual s (s |> String.toCodePoints |> String.ofCodePoints) +