membrain (empty) → 0.0.0.0
raw patch · 14 files changed
+1658/−0 lines, 14 filesdep +Globdep +basedep +doctest
Dependencies added: Glob, base, doctest, hedgehog, hspec, membrain, type-spec
Files
- CHANGELOG.md +11/−0
- LICENSE +373/−0
- README.md +47/−0
- membrain.cabal +101/−0
- src/Membrain.hs +27/−0
- src/Membrain/Base.hs +169/−0
- src/Membrain/Constructors.hs +211/−0
- src/Membrain/Memory.hs +322/−0
- src/Membrain/Units.hs +141/−0
- test/Doctest.hs +19/−0
- test/Spec.hs +31/−0
- test/Test/Memory/Laws.hs +93/−0
- test/Test/Memory/TypeLevel.hs +53/−0
- test/Test/Memory/ValueLevel.hs +60/−0
+ CHANGELOG.md view
@@ -0,0 +1,11 @@+# Changelog++`membrain` uses [PVP Versioning][1].+The changelog is available [on GitHub][2].++## 0.0.0.0 — 23 Jul, 2019++* Initially created.++[1]: https://pvp.haskell.org+[2]: https://github.com/kowainik/membrain/releases
+ LICENSE view
@@ -0,0 +1,373 @@+Mozilla Public License Version 2.0+==================================++1. Definitions+--------------++1.1. "Contributor"+ means each individual or legal entity that creates, contributes to+ the creation of, or owns Covered Software.++1.2. "Contributor Version"+ means the combination of the Contributions of others (if any) used+ by a Contributor and that particular Contributor's Contribution.++1.3. "Contribution"+ means Covered Software of a particular Contributor.++1.4. "Covered Software"+ means Source Code Form to which the initial Contributor has attached+ the notice in Exhibit A, the Executable Form of such Source Code+ Form, and Modifications of such Source Code Form, in each case+ including portions thereof.++1.5. "Incompatible With Secondary Licenses"+ means++ (a) that the initial Contributor has attached the notice described+ in Exhibit B to the Covered Software; or++ (b) that the Covered Software was made available under the terms of+ version 1.1 or earlier of the License, but not also under the+ terms of a Secondary License.++1.6. "Executable Form"+ means any form of the work other than Source Code Form.++1.7. "Larger Work"+ means a work that combines Covered Software with other material, in+ a separate file or files, that is not Covered Software.++1.8. "License"+ means this document.++1.9. "Licensable"+ means having the right to grant, to the maximum extent possible,+ whether at the time of the initial grant or subsequently, any and+ all of the rights conveyed by this License.++1.10. "Modifications"+ means any of the following:++ (a) any file in Source Code Form that results from an addition to,+ deletion from, or modification of the contents of Covered+ Software; or++ (b) any new file in Source Code Form that contains any Covered+ Software.++1.11. "Patent Claims" of a Contributor+ means any patent claim(s), including without limitation, method,+ process, and apparatus claims, in any patent Licensable by such+ Contributor that would be infringed, but for the grant of the+ License, by the making, using, selling, offering for sale, having+ made, import, or transfer of either its Contributions or its+ Contributor Version.++1.12. "Secondary License"+ means either the GNU General Public License, Version 2.0, the GNU+ Lesser General Public License, Version 2.1, the GNU Affero General+ Public License, Version 3.0, or any later versions of those+ licenses.++1.13. "Source Code Form"+ means the form of the work preferred for making modifications.++1.14. "You" (or "Your")+ means an individual or a legal entity exercising rights under this+ License. For legal entities, "You" includes any entity that+ controls, is controlled by, or is under common control with You. For+ purposes of this definition, "control" means (a) the power, direct+ or indirect, to cause the direction or management of such entity,+ whether by contract or otherwise, or (b) ownership of more than+ fifty percent (50%) of the outstanding shares or beneficial+ ownership of such entity.++2. License Grants and Conditions+--------------------------------++2.1. Grants++Each Contributor hereby grants You a world-wide, royalty-free,+non-exclusive license:++(a) under intellectual property rights (other than patent or trademark)+ Licensable by such Contributor to use, reproduce, make available,+ modify, display, perform, distribute, and otherwise exploit its+ Contributions, either on an unmodified basis, with Modifications, or+ as part of a Larger Work; and++(b) under Patent Claims of such Contributor to make, use, sell, offer+ for sale, have made, import, and otherwise transfer either its+ Contributions or its Contributor Version.++2.2. Effective Date++The licenses granted in Section 2.1 with respect to any Contribution+become effective for each Contribution on the date the Contributor first+distributes such Contribution.++2.3. Limitations on Grant Scope++The licenses granted in this Section 2 are the only rights granted under+this License. No additional rights or licenses will be implied from the+distribution or licensing of Covered Software under this License.+Notwithstanding Section 2.1(b) above, no patent license is granted by a+Contributor:++(a) for any code that a Contributor has removed from Covered Software;+ or++(b) for infringements caused by: (i) Your and any other third party's+ modifications of Covered Software, or (ii) the combination of its+ Contributions with other software (except as part of its Contributor+ Version); or++(c) under Patent Claims infringed by Covered Software in the absence of+ its Contributions.++This License does not grant any rights in the trademarks, service marks,+or logos of any Contributor (except as may be necessary to comply with+the notice requirements in Section 3.4).++2.4. Subsequent Licenses++No Contributor makes additional grants as a result of Your choice to+distribute the Covered Software under a subsequent version of this+License (see Section 10.2) or under the terms of a Secondary License (if+permitted under the terms of Section 3.3).++2.5. Representation++Each Contributor represents that the Contributor believes its+Contributions are its original creation(s) or it has sufficient rights+to grant the rights to its Contributions conveyed by this License.++2.6. Fair Use++This License is not intended to limit any rights You have under+applicable copyright doctrines of fair use, fair dealing, or other+equivalents.++2.7. Conditions++Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted+in Section 2.1.++3. Responsibilities+-------------------++3.1. Distribution of Source Form++All distribution of Covered Software in Source Code Form, including any+Modifications that You create or to which You contribute, must be under+the terms of this License. You must inform recipients that the Source+Code Form of the Covered Software is governed by the terms of this+License, and how they can obtain a copy of this License. You may not+attempt to alter or restrict the recipients' rights in the Source Code+Form.++3.2. Distribution of Executable Form++If You distribute Covered Software in Executable Form then:++(a) such Covered Software must also be made available in Source Code+ Form, as described in Section 3.1, and You must inform recipients of+ the Executable Form how they can obtain a copy of such Source Code+ Form by reasonable means in a timely manner, at a charge no more+ than the cost of distribution to the recipient; and++(b) You may distribute such Executable Form under the terms of this+ License, or sublicense it under different terms, provided that the+ license for the Executable Form does not attempt to limit or alter+ the recipients' rights in the Source Code Form under this License.++3.3. Distribution of a Larger Work++You may create and distribute a Larger Work under terms of Your choice,+provided that You also comply with the requirements of this License for+the Covered Software. If the Larger Work is a combination of Covered+Software with a work governed by one or more Secondary Licenses, and the+Covered Software is not Incompatible With Secondary Licenses, this+License permits You to additionally distribute such Covered Software+under the terms of such Secondary License(s), so that the recipient of+the Larger Work may, at their option, further distribute the Covered+Software under the terms of either this License or such Secondary+License(s).++3.4. Notices++You may not remove or alter the substance of any license notices+(including copyright notices, patent notices, disclaimers of warranty,+or limitations of liability) contained within the Source Code Form of+the Covered Software, except that You may alter any license notices to+the extent required to remedy known factual inaccuracies.++3.5. Application of Additional Terms++You may choose to offer, and to charge a fee for, warranty, support,+indemnity or liability obligations to one or more recipients of Covered+Software. However, You may do so only on Your own behalf, and not on+behalf of any Contributor. You must make it absolutely clear that any+such warranty, support, indemnity, or liability obligation is offered by+You alone, and You hereby agree to indemnify every Contributor for any+liability incurred by such Contributor as a result of warranty, support,+indemnity or liability terms You offer. You may include additional+disclaimers of warranty and limitations of liability specific to any+jurisdiction.++4. Inability to Comply Due to Statute or Regulation+---------------------------------------------------++If it is impossible for You to comply with any of the terms of this+License with respect to some or all of the Covered Software due to+statute, judicial order, or regulation then You must: (a) comply with+the terms of this License to the maximum extent possible; and (b)+describe the limitations and the code they affect. Such description must+be placed in a text file included with all distributions of the Covered+Software under this License. Except to the extent prohibited by statute+or regulation, such description must be sufficiently detailed for a+recipient of ordinary skill to be able to understand it.++5. Termination+--------------++5.1. The rights granted under this License will terminate automatically+if You fail to comply with any of its terms. However, if You become+compliant, then the rights granted under this License from a particular+Contributor are reinstated (a) provisionally, unless and until such+Contributor explicitly and finally terminates Your grants, and (b) on an+ongoing basis, if such Contributor fails to notify You of the+non-compliance by some reasonable means prior to 60 days after You have+come back into compliance. Moreover, Your grants from a particular+Contributor are reinstated on an ongoing basis if such Contributor+notifies You of the non-compliance by some reasonable means, this is the+first time You have received notice of non-compliance with this License+from such Contributor, and You become compliant prior to 30 days after+Your receipt of the notice.++5.2. If You initiate litigation against any entity by asserting a patent+infringement claim (excluding declaratory judgment actions,+counter-claims, and cross-claims) alleging that a Contributor Version+directly or indirectly infringes any patent, then the rights granted to+You by any and all Contributors for the Covered Software under Section+2.1 of this License shall terminate.++5.3. In the event of termination under Sections 5.1 or 5.2 above, all+end user license agreements (excluding distributors and resellers) which+have been validly granted by You or Your distributors under this License+prior to termination shall survive termination.++************************************************************************+* *+* 6. Disclaimer of Warranty *+* ------------------------- *+* *+* Covered Software is provided under this License on an "as is" *+* basis, without warranty of any kind, either expressed, implied, or *+* statutory, including, without limitation, warranties that the *+* Covered Software is free of defects, merchantable, fit for a *+* particular purpose or non-infringing. The entire risk as to the *+* quality and performance of the Covered Software is with You. *+* Should any Covered Software prove defective in any respect, You *+* (not any Contributor) assume the cost of any necessary servicing, *+* repair, or correction. This disclaimer of warranty constitutes an *+* essential part of this License. No use of any Covered Software is *+* authorized under this License except under this disclaimer. *+* *+************************************************************************++************************************************************************+* *+* 7. Limitation of Liability *+* -------------------------- *+* *+* Under no circumstances and under no legal theory, whether tort *+* (including negligence), contract, or otherwise, shall any *+* Contributor, or anyone who distributes Covered Software as *+* permitted above, be liable to You for any direct, indirect, *+* special, incidental, or consequential damages of any character *+* including, without limitation, damages for lost profits, loss of *+* goodwill, work stoppage, computer failure or malfunction, or any *+* and all other commercial damages or losses, even if such party *+* shall have been informed of the possibility of such damages. This *+* limitation of liability shall not apply to liability for death or *+* personal injury resulting from such party's negligence to the *+* extent applicable law prohibits such limitation. Some *+* jurisdictions do not allow the exclusion or limitation of *+* incidental or consequential damages, so this exclusion and *+* limitation may not apply to You. *+* *+************************************************************************++8. Litigation+-------------++Any litigation relating to this License may be brought only in the+courts of a jurisdiction where the defendant maintains its principal+place of business and such litigation shall be governed by laws of that+jurisdiction, without reference to its conflict-of-law provisions.+Nothing in this Section shall prevent a party's ability to bring+cross-claims or counter-claims.++9. Miscellaneous+----------------++This License represents the complete agreement concerning the subject+matter hereof. If any provision of this License is held to be+unenforceable, such provision shall be reformed only to the extent+necessary to make it enforceable. Any law or regulation which provides+that the language of a contract shall be construed against the drafter+shall not be used to construe this License against a Contributor.++10. Versions of the License+---------------------------++10.1. New Versions++Mozilla Foundation is the license steward. Except as provided in Section+10.3, no one other than the license steward has the right to modify or+publish new versions of this License. Each version will be given a+distinguishing version number.++10.2. Effect of New Versions++You may distribute the Covered Software under the terms of the version+of the License under which You originally received the Covered Software,+or under the terms of any subsequent version published by the license+steward.++10.3. Modified Versions++If you create software not governed by this License, and you want to+create a new license for such software, you may create and use a+modified version of this License if you rename the license and remove+any references to the name of the license steward (except to note that+such modified license differs from this License).++10.4. Distributing Source Code Form that is Incompatible With Secondary+Licenses++If You choose to distribute Source Code Form that is Incompatible With+Secondary Licenses under the terms of this version of the License, the+notice described in Exhibit B of this License must be attached.++Exhibit A - Source Code Form License Notice+-------------------------------------------++ This Source Code Form is subject to the terms of the Mozilla Public+ License, v. 2.0. If a copy of the MPL was not distributed with this+ file, You can obtain one at http://mozilla.org/MPL/2.0/.++If it is not possible or desirable to put the notice in a particular+file, then You may include the notice in a location (such as a LICENSE+file in a relevant directory) where a recipient would be likely to look+for such a notice.++You may add additional accurate notices of copyright ownership.++Exhibit B - "Incompatible With Secondary Licenses" Notice+---------------------------------------------------------++ This Source Code Form is "Incompatible With Secondary Licenses", as+ defined by the Mozilla Public License, v. 2.0.
+ README.md view
@@ -0,0 +1,47 @@+# membrain+++[](https://travis-ci.org/kowainik/membrain)+[](https://hackage.haskell.org/package/membrain)+[](http://stackage.org/lts/package/membrain)+[](http://stackage.org/nightly/package/membrain)+[](LICENSE)++> "People think dreams aren't real just because they aren't made of matter, of particles.+> Dreams are real. But they are made of viewpoints, of images, of memories and puns and lost hopes."+>+> ― Neil Gaiman++This package implements type-safe memory units. It pursues the following goals:++1. Focus on correctness.+2. Low amount of boilerplate should be required to use the library.++The ideas behind this package are described in the following blog post:++ * [Insane in the Membrain](https://kowainik.github.io/posts/membrain)++The library is built around the following data type:++```haskell+newtype Memory (mem :: Nat) = Memory+ { unMemory :: Natural+ }+```++This data type stores every memory internally as bits. However, unit multiplier+is stored as type-level natural number. This approach allows to represent+different units and implement instances for them with low amount of boilerplate.++`membrain` implements various useful functions to work with `Memory`:++1. Smart constructors.+2. Conversion functions.+3. Pretty displaying.+4. Dependently-typed parsing.+5. Numeric functions.+6. Type-safe wrappers around functions from `base`.++## Acknowledgement++Icons made by [Kiranshastry](https://www.flaticon.com/authors/kiranshastry) from [Flaticon](https://www.flaticon.com/) is licensed by [CC 3.0 BY](http://creativecommons.org/licenses/by/3.0/).
+ membrain.cabal view
@@ -0,0 +1,101 @@+cabal-version: 2.4+name: membrain+version: 0.0.0.0+synopsis: Type-safe memory units+description:+ @membrain@ provides @newtype@ wrapper for type-safe work with memory units+ .+ @+ __newtype__ Memory (mem :: Nat) = Memory+ \ { unMemory :: Natural+ \ }+ @+ .+ This data type stores memory unit value phantom type parameter which is+ represented as type-level natural number.++ The ideas behind this package are described in the following blog post:+ .+ * [Insane in the Membrain](https://kowainik.github.io/posts/membrain)++homepage: https://github.com/kowainik/membrain+bug-reports: https://github.com/kowainik/membrain/issues+license: MPL-2.0+license-file: LICENSE+author: Veronika Romashkina, Dmitrii Kovanikov+maintainer: Kowainik <xrom.xkov@gmail.com>+copyright: 2018-2019 Kowainik+category: Memory, Safe+build-type: Simple+extra-doc-files: README.md+ , CHANGELOG.md+tested-with: GHC == 8.2.2+ , GHC == 8.4.4+ , GHC == 8.6.5++source-repository head+ type: git+ location: https://github.com/kowainik/membrain.git++common common-options+ build-depends: base >= 4.10.1.0 && < 4.13++ ghc-options: -Wall+ -Wincomplete-uni-patterns+ -Wincomplete-record-updates+ -Wcompat+ -Widentities+ -Wredundant-constraints+ -fhide-source-paths+ -Wmissing-export-lists+ -Wpartial-fields++ default-language: Haskell2010+ default-extensions: ConstraintKinds+ DeriveGeneric+ InstanceSigs+ GeneralizedNewtypeDeriving+ LambdaCase+ OverloadedStrings+ RecordWildCards+ ScopedTypeVariables+ StandaloneDeriving+ TupleSections+ TypeApplications+ ViewPatterns++library+ import: common-options+ hs-source-dirs: src+ exposed-modules: Membrain+ Membrain.Base+ Membrain.Constructors+ Membrain.Memory+ Membrain.Units++test-suite membrain-test+ import: common-options+ type: exitcode-stdio-1.0+ hs-source-dirs: test+ main-is: Spec.hs+ other-modules: Test.Memory.Laws+ Test.Memory.TypeLevel+ Test.Memory.ValueLevel++ build-depends: membrain+ , hedgehog ^>= 1.0+ , hspec ^>= 2.7.1+ , type-spec ^>= 0.4.0.0++ ghc-options: -threaded -rtsopts -with-rtsopts=-N++test-suite doctest+ import: common-options+ type: exitcode-stdio-1.0+ hs-source-dirs: test+ main-is: Doctest.hs++ build-depends: doctest ^>= 0.16+ , Glob++ ghc-options: -threaded
+ src/Membrain.hs view
@@ -0,0 +1,27 @@+{- | Type-safe memory units. This package has the following structure:++* __"Membrain.Memory":__ main 'Memory' data type with many utility functions.+* __"Membrain.Units":__ type-level unit multipliers.+* __"Membrain.Constructors":__ smart constructors for creating values of type+ 'Memory'.+* __"Membrain.Base":__ type-safe versions of functions from @base@ that work+ with memory-related values.++@membrain@ aims for qualified imports. Import as follows:++@+__import__ __qualified__ Membrain __as__ Mem+@+-}++module Membrain+ ( module Membrain.Base+ , module Membrain.Constructors+ , module Membrain.Memory+ , module Membrain.Units+ ) where++import Membrain.Base+import Membrain.Constructors+import Membrain.Memory+import Membrain.Units
+ src/Membrain/Base.hs view
@@ -0,0 +1,169 @@+{- |+This modules introduces more type-safe interface of some standard function to+work with memory from @base@ package.+-}++module Membrain.Base+ ( -- * "System.IO" module+ hFileSize+ , hSetFileSize++ -- * "Data.Bits" module+ , bitSizeMaybe+ , finiteBitSize++ -- * "Foreign" module+ , sizeOf+ , allocaBytes+ , mallocBytes+ , callocBytes+ , reallocBytes+ , mallocForeignPtrBytes+ ) where++import Data.Bits (FiniteBits)+import Foreign.ForeignPtr (ForeignPtr)+import Foreign.Ptr (Ptr)+import Foreign.Storable (Storable)+import Prelude hiding (floor)+import System.IO (Handle)++import Membrain.Constructors (bit, byte)+import Membrain.Memory (Memory, floor)+import Membrain.Units (Bit, Byte)++import qualified Data.Bits as Base (Bits, bitSizeMaybe, finiteBitSize)+import qualified Foreign.ForeignPtr as Base (mallocForeignPtrBytes)+import qualified Foreign.Marshal.Alloc as Base (allocaBytes, callocBytes, mallocBytes, reallocBytes)+import qualified Foreign.Storable as Base+import qualified System.IO as Base (hFileSize, hSetFileSize)+++----------------------------------------------------------------------------+-- System.IO+----------------------------------------------------------------------------++{- | For a handle which attached to a physical file, the function returns the+size of that file in 'Byte's.++Similar 'Base.hFileSize' from @base@ but more type-safe: returns 'Memory Byte'+instead of 'Integer'.+-}+hFileSize :: Handle -> IO (Memory Byte)+hFileSize h = byte . fromInteger <$> Base.hFileSize h+{-# INLINE hFileSize #-}++{- | Truncates the physical file with the handle to the given size in 'Byte's.++Similar to 'Base.hSetFileSize' from @base@ but more type-safe: it works with+given 'Memory Byte' instead of 'Integer'.++__NOTE:__ This function makes 'floor' under the hood, so be careful when working+with the smaller units.+-}+hSetFileSize :: Handle -> Memory Byte -> IO ()+hSetFileSize h = Base.hSetFileSize h . floor+{-# INLINE hSetFileSize #-}++----------------------------------------------------------------------------+-- Data.Bits+----------------------------------------------------------------------------++{- | Returns the number of 'Bit's in the type of the argument. The actual value of+the argument is ignored. Returns 'Nothing' for types that do not have a fixed+bitsize, like 'Integer'.++Type safe version of the 'Base.bitSizeMaybe' function.++>>> bitSizeMaybe (0 :: Int)+Just (Memory {unMemory = 64})+>>> bitSizeMaybe (0 :: Integer)+Nothing+-}+bitSizeMaybe :: Base.Bits a => a -> Maybe (Memory Bit)+bitSizeMaybe x = bit . fromIntegral <$> Base.bitSizeMaybe x+{-# INLINE bitSizeMaybe #-}++{- | Return the number of bits in the type of the argument. The actual value of the argument is ignored.++Type safe version of the 'Base.finiteBitSize' function.++>>> finiteBitSize False+Memory {unMemory = 1}+>>> finiteBitSize (0 :: Int)+Memory {unMemory = 64}+-}+finiteBitSize :: FiniteBits b => b -> Memory Bit+finiteBitSize = bit . fromIntegral . Base.finiteBitSize+{-# INLINE finiteBitSize #-}++----------------------------------------------------------------------------+-- Foreign.Storable+----------------------------------------------------------------------------++{- | Like 'Base.sizeOf' but returns type-safe 'Memory Byte' instead of the 'Int'+which represents the amount of bytes.++Computes the storage requirements (in bytes) of the argument. The value of the+argument is not used.++>>> sizeOf True+Memory {unMemory = 32}+>>> sizeOf 'x'+Memory {unMemory = 32}+>>> sizeOf (0 :: Int)+Memory {unMemory = 64}+>>> sizeOf (0.0 :: Double)+Memory {unMemory = 64}+-}+sizeOf :: Storable a => a -> Memory Byte+sizeOf = byte . fromIntegral . Base.sizeOf+{-# INLINE sizeOf #-}++----------------------------------------------------------------------------+-- Foreign.Marshal.Alloc+----------------------------------------------------------------------------++{- | Executes the computation, passing as argument a pointer to a temporarily+allocated block of memory of @n@ 'Byte's. The block of memory is sufficiently+aligned for any of the basic foreign types that fits into a memory block of the+allocated size.++The memory is freed when the computation terminates (either normally or via+an exception), so the passed pointer must not be used after this.++Similar to 'Base.allocaBytes' but receives 'Byte's instead of 'Int'.+-}+allocaBytes :: Memory Byte -> (Ptr a -> IO b) -> IO b+allocaBytes bs = Base.allocaBytes (floor bs)+{-# INLINE allocaBytes #-}++{- | Allocates a block of memory of the given number of 'Byte's.+The block of memory is sufficiently aligned for any of the basic foreign types+that fits into a memory block of the allocated size.++Similar to 'Base.mallocBytes' but receives 'Byte's instead of 'Int'.+-}+mallocBytes :: Memory Byte -> IO (Ptr a)+mallocBytes = Base.mallocBytes . floor+{-# INLINE mallocBytes #-}++{- | Llike 'mallocBytes' but memory is filled with 'Byte's of value zero.+-}+callocBytes :: Memory Byte -> IO (Ptr a)+callocBytes = Base.callocBytes . floor+{-# INLINE callocBytes #-}++{- | Type safe version of the 'Base.reallocBytes' function. -}+reallocBytes :: Ptr a -> Memory Byte -> IO (Ptr a)+reallocBytes p = Base.reallocBytes p . floor+{-# INLINE reallocBytes #-}++----------------------------------------------------------------------------+-- Foreign.ForeignPtr+----------------------------------------------------------------------------++{- | Type safe version of the 'Base.mallocForeignPtrBytes' function. -}+mallocForeignPtrBytes :: Memory Byte -> IO (ForeignPtr a)+mallocForeignPtrBytes = Base.mallocForeignPtrBytes . floor+{-# INLINE mallocForeignPtrBytes #-}
+ src/Membrain/Constructors.hs view
@@ -0,0 +1,211 @@+{- | This module implements smart constructors for creating values of type+'Memory'.+-}++module Membrain.Constructors+ ( -- * Smart constructors+ bit+ , nibble+ , byte++ , kilobyte+ , megabyte+ , gigabyte+ , terabyte+ , petabyte+ , exabyte+ , zettabyte+ , yottabyte++ , kibibyte+ , mebibyte+ , gibibyte+ , tebibyte+ , pebibyte+ , exbibyte+ , zebibyte+ , yobibyte+ ) where++import GHC.Natural (Natural)++import Membrain.Memory (Memory (..), memory)+import Membrain.Units (Bit, Byte, Exabyte, Exbibyte, Gibibyte, Gigabyte, Kibibyte, Kilobyte,+ Mebibyte, Megabyte, Nibble, Pebibyte, Petabyte, Tebibyte, Terabyte, Yobibyte,+ Yottabyte, Zebibyte, Zettabyte)+++{- $setup+>>> import Membrain+-}++{- | Creates 'Memory' in 'Bit's from given 'Natural' as the number of bits.++>>> showMemory $ bit 42+"42b"+-}+bit :: Natural -> Memory Bit+bit = Memory+{-# INLINE bit #-}++{- | Creates 'Memory' in 'Nibble's from given 'Natural' as the number of nibbles.++>>> showMemory $ nibble 42+"42n"+-}+nibble :: Natural -> Memory Nibble+nibble = memory+{-# INLINE nibble #-}++{- | Creates 'Memory' in 'Byte's from given 'Natural' as the number of bytes.++>>> showMemory $ byte 42+"42B"+-}+byte :: Natural -> Memory Byte+byte = memory+{-# INLINE byte #-}++{- | Creates 'Memory' in 'Kilobyte's from given 'Natural' as the number of kilobytes.++>>> showMemory $ kilobyte 42+"42kB"+-}+kilobyte :: Natural -> Memory Kilobyte+kilobyte = memory+{-# INLINE kilobyte #-}++{- | Creates 'Memory' in 'Megabyte's from given 'Natural' as the number of megabytes.++>>> showMemory $ megabyte 42+"42MB"+-}+megabyte :: Natural -> Memory Megabyte+megabyte = memory+{-# INLINE megabyte #-}++{- | Creates 'Memory' in 'Gigabyte's from given 'Natural' as the number of gigabytes.++>>> showMemory $ gigabyte 42+"42GB"+-}+gigabyte :: Natural -> Memory Gigabyte+gigabyte = memory+{-# INLINE gigabyte #-}++{- | Creates 'Memory' in 'Terabyte's from given 'Natural' as the number of terabytes.++>>> showMemory $ terabyte 42+"42TB"+-}+terabyte :: Natural -> Memory Terabyte+terabyte = memory+{-# INLINE terabyte #-}++{- | Creates 'Memory' in 'Petabyte's from given 'Natural' as the number of petabytes.++>>> showMemory $ petabyte 42+"42PB"+-}+petabyte :: Natural -> Memory Petabyte+petabyte = memory+{-# INLINE petabyte #-}++{- | Creates 'Memory' in 'Exabyte's from given 'Natural' as the number of exabytes.++>>> showMemory $ exabyte 42+"42EB"+-}+exabyte :: Natural -> Memory Exabyte+exabyte = memory+{-# INLINE exabyte #-}++{- | Creates 'Memory' in 'Zettabyte's from given 'Natural' as the number of zettabytes.++>>> showMemory $ zettabyte 42+"42ZB"+-}+zettabyte :: Natural -> Memory Zettabyte+zettabyte = memory+{-# INLINE zettabyte #-}++{- | Creates 'Memory' in 'Yottabyte's from given 'Natural' as the number of yottabytes.++>>> showMemory $ yottabyte 42+"42YB"+-}+yottabyte :: Natural -> Memory Yottabyte+yottabyte = memory+{-# INLINE yottabyte #-}++{- | Creates 'Memory' in 'Kibibyte's from given 'Natural' as the number of kibibytes.++>>> showMemory $ kibibyte 42+"42KiB"+-}+kibibyte :: Natural -> Memory Kibibyte+kibibyte = memory+{-# INLINE kibibyte #-}++{- | Creates 'Memory' in 'Mebibyte's from given 'Natural' as the number of mebibytes.++>>> showMemory $ mebibyte 42+"42MiB"+-}+mebibyte :: Natural -> Memory Mebibyte+mebibyte = memory+{-# INLINE mebibyte #-}++{- | Creates 'Memory' in 'Gibibyte's from given 'Natural' as the number of gibibytes.++>>> showMemory $ gibibyte 42+"42GiB"+-}+gibibyte :: Natural -> Memory Gibibyte+gibibyte = memory+{-# INLINE gibibyte #-}++{- | Creates 'Memory' in 'Tebibyte's from given 'Natural' as the number of tebibytes.++>>> showMemory $ tebibyte 42+"42TiB"+-}+tebibyte :: Natural -> Memory Tebibyte+tebibyte = memory+{-# INLINE tebibyte #-}++{- | Creates 'Memory' in 'Pebibyte's from given 'Natural' as the number of pebibytes.++>>> showMemory $ pebibyte 42+"42PiB"+-}+pebibyte :: Natural -> Memory Pebibyte+pebibyte = memory+{-# INLINE pebibyte #-}++{- | Creates 'Memory' in 'Exbibyte's from given 'Natural' as the number of exbibytes.++>>> showMemory $ exbibyte 42+"42EiB"+-}+exbibyte :: Natural -> Memory Exbibyte+exbibyte = memory+{-# INLINE exbibyte #-}++{- | Creates 'Memory' in 'Zebibyte's from given 'Natural' as the number of zebibytes.++>>> showMemory $ zebibyte 42+"42ZiB"+-}+zebibyte :: Natural -> Memory Zebibyte+zebibyte = memory+{-# INLINE zebibyte #-}++{- | Creates 'Memory' in 'Yobibyte's from given 'Natural' as the number of yobibytes.++>>> showMemory $ yobibyte 42+"42YiB"+-}+yobibyte :: Natural -> Memory Yobibyte+yobibyte = memory+{-# INLINE yobibyte #-}
+ src/Membrain/Memory.hs view
@@ -0,0 +1,322 @@+{-# LANGUAGE AllowAmbiguousTypes #-}+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE DerivingStrategies #-}+{-# LANGUAGE ExistentialQuantification #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE TypeInType #-}+{-# LANGUAGE UndecidableInstances #-}++{- | This module contains 'Memory' data type and various utility functions:++1. Create values of type 'Memory'.+2. Unwrap values of type 'Memory' to integral types.+3. Pretty-displaying functions.+4. Parsing.+5. Numeric functions.+-}++module Membrain.Memory+ ( -- * Data type+ Memory (..)+ , memory+ , toMemory+ , showMemory+ , readMemory++ -- * Conversion functions+ , toBits+ , toRat+ , floor++ -- * Numeric operations+ , memoryMul+ , memoryDiff+ , memoryPlus+ , memoryDiv++ -- * Any memory data type+ -- $any+ , AnyMemory (..)+ ) where++import Prelude hiding (floor)++import Data.Char (isDigit, isSpace)+import Data.Coerce (coerce)+import Data.Foldable (foldl')+import Data.Kind (Type)+import Data.List.NonEmpty (NonEmpty)+import Data.Proxy (Proxy (..))+import Data.Ratio (Ratio, (%))+import Data.Semigroup (Semigroup (..))+import GHC.Generics (Generic)+import GHC.TypeNats (KnownNat, Nat, natVal)+import Numeric.Natural (Natural)++import Membrain.Units (KnownUnitSymbol, unitSymbol)++import qualified Prelude+++{- $setup+>>> import Membrain+-}++{- | Main memory units type. It has phantom type parameter @mem@ of kind 'Nat'+which is type level representation of the unit. Stores internally memory as+bits. To construct values of type 'Memory', use functions from the+"Membrain.Constructors" module.+-}+newtype Memory (mem :: Nat) = Memory+ { unMemory :: Natural+ } deriving stock (Show, Read, Generic)+ deriving newtype (Eq, Ord)++{- | Semigroup over addition.++>>> byte 2 <> byte 5+Memory {unMemory = 56}+-}+instance Semigroup (Memory (mem :: Nat)) where+ (<>) :: Memory mem -> Memory mem -> Memory mem+ (<>) = coerce ((+) @Natural)+ {-# INLINE (<>) #-}++ sconcat :: NonEmpty (Memory mem) -> Memory mem+ sconcat = foldl' (<>) mempty+ {-# INLINE sconcat #-}++ stimes :: Integral b => b -> Memory mem -> Memory mem+ stimes n (Memory m) = Memory (fromIntegral n * m)+ {-# INLINE stimes #-}++instance Monoid (Memory (mem :: Nat)) where+ mempty :: Memory mem+ mempty = Memory 0+ {-# INLINE mempty #-}++ mappend :: Memory mem -> Memory mem -> Memory mem+ mappend = (<>)+ {-# INLINE mappend #-}++ mconcat :: [Memory mem] -> Memory mem+ mconcat = foldl' (<>) mempty+ {-# INLINE mconcat #-}++{- |+This 'showMemory' function shows a 'Memory' value as 'Double' along with the+measure unit suffix. It shows 'Memory' losslessly while used with standardized+units of measurements. The following mathematical law is used to display+'Memory':++A decimal representation written with a repeating final @0@ is supposed to+terminate before these zeros. Instead of @1.585000...@ one simply writes+@1.585@. The decimal is also called a terminating decimal. Terminating decimals+represent rational numbers of the form \( \cfrac{k}{2^n 5^m} \). If you use+different forms of units then the 'show' function for 'Memory' hangs.++>>> showMemory (Memory 22 :: Memory Byte)+"2.75B"+-}+showMemory :: forall mem . (KnownNat mem, KnownUnitSymbol mem) => Memory mem -> String+showMemory (Memory m) = showFrac m (nat @mem) ++ unitSymbol @mem+ where+ showFrac :: Natural -> Natural -> String+ showFrac number d = goIntegral number+ where+ -- take integral part of fraction+ goIntegral :: Natural -> String+ goIntegral n =+ let (q, r) = n `divMod` d+ integral = show q+ in if r == 0+ then integral+ else integral ++ '.' : goFractional r++ -- convert reminder to fractional part+ goFractional :: Natural -> String+ goFractional 0 = ""+ goFractional n =+ let (q, r) = (n * 10) `divMod` d+ in show q ++ goFractional r+++{- | Inverse of 'showMemory'.++>>> readMemory @Byte "2.75B"+Just (Memory {unMemory = 22})+>>> readMemory @Bit "2.75B"+Nothing+-}+readMemory+ :: forall (mem :: Nat)+ . (KnownUnitSymbol mem, KnownNat mem)+ => String+ -> Maybe (Memory mem)+readMemory (dropWhile isSpace -> str) = case span isDigit str of+ ([], _) -> Nothing+ (_, []) -> Nothing+ (ds, '.': rest) -> case span isDigit rest of+ ([], _) -> Nothing+ (numerator, unit) -> makeMemory ds numerator unit+ (ds, unit) -> makeMemory ds "0" unit+ where+ makeMemory :: String -> String -> String -> Maybe (Memory mem)+ makeMemory (read @Natural -> whole) numStr u =+ if unitSymbol @mem == u+ then case ((whole * numPow + num) * unit) `divMod` numPow of+ (b, 0) -> Just $ Memory b+ _ -> Nothing+ else Nothing+ where+ unit :: Natural+ unit = nat @mem++ num :: Natural+ num = read @Natural numStr++ numPow :: Natural+ numPow = 10 ^ length numStr++{- | Creates 'Memory' of unit @mem@ by the given 'Natural' number. 'Memory's+smart constructor.++>>> memory @Byte 3+Memory {unMemory = 24}+-}+memory :: forall (mem :: Nat) . KnownNat mem => Natural -> Memory mem+memory = Memory . (* nat @mem)+{-# INLINE memory #-}++{- | Convert memory from one unit to another.++__Note:__ this changes only view, not model.+So this operation has zero runtime cost.++>>> showMemory $ toMemory @Kilobyte $ byte 100+"0.1kB"+>>> showMemory $ toMemory @Kibibyte $ byte 100+"0.09765625KiB"+-}+toMemory :: forall (to :: Nat) (from :: Nat) . Memory from -> Memory to+toMemory = coerce+{-# INLINE toMemory #-}++{- | Lossless 'Memory' conversion to bits. Alias to 'unMemory'.++>>> toBits $ byte 1+8+>>> toBits $ kilobyte 1+8000+-}+toBits :: Memory mem -> Natural+toBits = coerce+{-# INLINE toBits #-}++{- | Lossless 'Memory' conversion to rational number.++>>> toRat $ byte 4+4 % 1+>>> toRat $ toMemory @Byte $ bit 22+11 % 4+-}+toRat :: forall (mem :: Nat) . KnownNat mem => Memory mem -> Ratio Natural+toRat (Memory m) = m % nat @mem+{-# INLINE toRat #-}++{- | Floor 'Memory' unit to integral number. This function may lose some+information, so use only when:++1. You don't care about losing information.+2. You are sure that there will be no loss.++>>> floor $ byte 4+4+>>> floor $ toMemory @Byte $ bit 22+2+-}+floor+ :: forall (n :: Type) (mem :: Nat) .+ (Integral n, KnownNat mem)+ => Memory mem+ -> n+floor = Prelude.floor . toRat+{-# INLINE floor #-}+{-# SPECIALIZE floor :: KnownNat mem => Memory mem -> Int #-}+{-# SPECIALIZE floor :: KnownNat mem => Memory mem -> Word #-}+{-# SPECIALIZE floor :: KnownNat mem => Memory mem -> Integer #-}+{-# SPECIALIZE floor :: KnownNat mem => Memory mem -> Natural #-}++----------------------------------------------------------------------------+-- Numeric functions+----------------------------------------------------------------------------++{- | Returns the result of multiplication 'Natural' with the given 'Memory' value++>>> memoryMul 2 (byte 4)+Memory {unMemory = 64}+-}+memoryMul :: Natural -> Memory mem -> Memory mem+memoryMul = stimes+{-# INLINE memoryMul #-}++{- | Returns the result of comparison of two 'Memory' values+and the difference between them as another 'Memory' of the same unit.++>>> memoryDiff (bit 4) (bit 8)+(LT,Memory {unMemory = 4})+>>> memoryDiff (byte 8) (byte 4)+(GT,Memory {unMemory = 32})+>>> memoryDiff (kilobyte 2) (kilobyte 2)+(EQ,Memory {unMemory = 0})+-}+memoryDiff :: Memory mem -> Memory mem -> (Ordering, Memory mem)+memoryDiff (Memory m1) (Memory m2) = case compare m1 m2 of+ LT -> (LT, Memory $ m2 - m1)+ GT -> (GT, Memory $ m1 - m2)+ EQ -> (EQ, Memory 0)+{-# INLINE memoryDiff #-}++{- | Returns the result of addition of two 'Memory' values casted+to the second memory unit.++>>> memoryPlus (bit 8) (megabyte 2)+Memory {unMemory = 16000008}+-}+memoryPlus :: Memory mem1 -> Memory mem2 -> Memory mem2+memoryPlus m1 = (<>) (toMemory m1)+{-# INLINE memoryPlus #-}++{- | Retuns the result of division of two 'Memory' values of any units.++>>> memoryDiv (kilobyte 3) (byte 2)+1500 % 1+-}+memoryDiv :: Memory mem1 -> Memory mem2 -> Ratio Natural+memoryDiv (Memory m1) (Memory m2) = m1 % m2+{-# INLINE memoryDiv #-}++----------------------------------------------------------------------------+-- AnyMemory+----------------------------------------------------------------------------++{- $any+This data type is useful for working with 'Memory' of different units in+collections, or when 'Memory' of non-specified unit can be returned.+-}++-- | Existential data type for 'Memory's.+data AnyMemory+ = forall (mem :: Nat) . (KnownNat mem, KnownUnitSymbol mem)+ => MkAnyMemory (Memory mem)++instance Show AnyMemory where+ show (MkAnyMemory t) = showMemory t++----------------------------------------------------------------------------+-- Internal+----------------------------------------------------------------------------++nat :: forall (mem :: Nat) . KnownNat mem => Natural+nat = natVal (Proxy @mem)+{-# INLINE nat #-}
+ src/Membrain/Units.hs view
@@ -0,0 +1,141 @@+{-# LANGUAGE AllowAmbiguousTypes #-}+{-# LANGUAGE CPP #-}+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE TypeFamilyDependencies #-}+{-# LANGUAGE TypeOperators #-}+#if ( __GLASGOW_HASKELL__ >= 806 )+{-# LANGUAGE NoStarIsType #-}+#endif++{- | This module contains type aliases for memory data units. According to the+official standard, there exist two naming conventions for memory units. Standard+measure prefixes are multipliers of @10@. But there are alternative prefixes+which end with @bi@ and they are represented as powers of @2@. The difference+can be displayed in the following table:++ +------------+----------------+----------++ | Name | Multipliers | In bytes |+ +============+================+==========++ | 'Kilobyte' | \( 10 ^ 3 \) | 1000 |+ +------------+----------------+----------++ | 'Kibibyte' | \( 2 ^ {10} \) | 1024 |+ +------------+----------------+----------++ | 'Megabyte' | \( 10 ^ 6 \) | 1000000 |+ +------------+----------------+----------++ | 'Mebibyte' | \( 2 ^ {20} \) | 1048576 |+ +------------+----------------+----------++-}++module Membrain.Units+ ( -- * Simple+ Bit+ , Nibble+ , Byte++ -- * Decimal+ , Kilobyte+ , Megabyte+ , Gigabyte+ , Terabyte+ , Petabyte+ , Exabyte+ , Zettabyte+ , Yottabyte++ -- * Binary+ , Kibibyte+ , Mebibyte+ , Gibibyte+ , Tebibyte+ , Pebibyte+ , Exbibyte+ , Zebibyte+ , Yobibyte++ -- * Unit symbols+ , UnitSymbol+ , KnownUnitSymbol+ , unitSymbol+ ) where++import Data.Proxy (Proxy (..))+import GHC.TypeLits (KnownSymbol, Symbol, symbolVal)+import GHC.TypeNats (type (*), Nat)+++type Bit = 1+type Nibble = 4+type Byte = 8++type Kilobyte = 1000 * Byte+type Megabyte = 1000 * Kilobyte+type Gigabyte = 1000 * Megabyte+type Terabyte = 1000 * Gigabyte+type Petabyte = 1000 * Terabyte+type Exabyte = 1000 * Petabyte+type Zettabyte = 1000 * Exabyte+type Yottabyte = 1000 * Zettabyte++type Kibibyte = 1024 * Byte+type Mebibyte = 1024 * Kibibyte+type Gibibyte = 1024 * Mebibyte+type Tebibyte = 1024 * Gibibyte+type Pebibyte = 1024 * Tebibyte+type Exbibyte = 1024 * Pebibyte+type Zebibyte = 1024 * Exbibyte+type Yobibyte = 1024 * Zebibyte++{- | Type-level function to map memory units multipliers to proper symbols.++>>> :kind! UnitSymbol Bit+UnitSymbol Bit :: Symbol+= "b"+>>> :kind! UnitSymbol Byte+UnitSymbol Byte :: Symbol+= "B"+>>> :kind! UnitSymbol Kilobyte+UnitSymbol Kilobyte :: Symbol+= "kB"+>>> :kind! UnitSymbol Mebibyte+UnitSymbol Mebibyte :: Symbol+= "MiB"+-}+type family UnitSymbol (unit :: Nat) = (res :: Symbol) | res -> unit++type instance UnitSymbol 1 = "b"+type instance UnitSymbol 4 = "n"+type instance UnitSymbol 8 = "B"++type instance UnitSymbol 8000 = "kB"+type instance UnitSymbol 8000000 = "MB"+type instance UnitSymbol 8000000000 = "GB"+type instance UnitSymbol 8000000000000 = "TB"+type instance UnitSymbol 8000000000000000 = "PB"+type instance UnitSymbol 8000000000000000000 = "EB"+type instance UnitSymbol 8000000000000000000000 = "ZB"+type instance UnitSymbol 8000000000000000000000000 = "YB"++type instance UnitSymbol 8192 = "KiB"+type instance UnitSymbol 8388608 = "MiB"+type instance UnitSymbol 8589934592 = "GiB"+type instance UnitSymbol 8796093022208 = "TiB"+type instance UnitSymbol 9007199254740992 = "PiB"+type instance UnitSymbol 9223372036854775808 = "EiB"+type instance UnitSymbol 9444732965739290427392 = "ZiB"+type instance UnitSymbol 9671406556917033397649408 = "YiB"++-- | Constraint alias for 'KnownSymbol' calculated by 'UnitSymbol'.+type KnownUnitSymbol (mem :: Nat) = KnownSymbol (UnitSymbol mem)++{- | Term-level function to get value of the 'UnitSymbol' type family. Can be used+only with @-XTypeApplications@.++>>> unitSymbol @Terabyte+"TB"+>>> unitSymbol @Yobibyte+"YiB"+-}+unitSymbol :: forall (mem :: Nat) . KnownUnitSymbol mem => String+unitSymbol = symbolVal $ Proxy @(UnitSymbol mem)+{-# INLINE unitSymbol #-}
+ test/Doctest.hs view
@@ -0,0 +1,19 @@+module Main (main) where++import System.FilePath.Glob (glob)+import Test.DocTest (doctest)+++main :: IO ()+main = do+ sourceFiles <- glob "src/**/*.hs"+ doctest+ $ "-XConstraintKinds"+ : "-XInstanceSigs"+ : "-XScopedTypeVariables"+ : "-XTypeApplications"+ : "-XViewPatterns"+ : "-XDerivingStrategies"+ : "-XGeneralizedNewtypeDeriving"+ : "-XDeriveGeneric"+ : sourceFiles
+ test/Spec.hs view
@@ -0,0 +1,31 @@+module Main (main) where++import Hedgehog (Group (..), checkParallel)+import System.Exit (exitFailure, exitSuccess)+import System.IO (hSetEncoding, stderr, stdout, utf8)+import Test.Hspec (hspec)++import Test.Memory.Laws (monoidIdentityLaw, semigroupLaw, showReadLaw)+import Test.Memory.TypeLevel (runTypeLevelTests)+import Test.Memory.ValueLevel (unitTests)+++main :: IO ()+main = do+ -- fix terminal encoding+ hSetEncoding stdout utf8+ hSetEncoding stderr utf8++ runTypeLevelTests+ hspec unitTests+ checkParallel hedgehogTests >>= \p -> if p then exitSuccess else exitFailure++hedgehogTests :: Group+hedgehogTests = Group "Roundtrip properties"+ [ semigroupLaw `named` "Semigroup: x <> (y <> z) ≡ (x <> y) <> z"+ , monoidIdentityLaw `named` "Monoid Identity: x <> mempty ≡ x"+ , showReadLaw `named` "read . show x ≡ Just x"+ ]+ where+ named :: a -> b -> (b, a)+ named = flip (,)
+ test/Test/Memory/Laws.hs view
@@ -0,0 +1,93 @@+module Test.Memory.Laws+ ( semigroupLaw+ , monoidIdentityLaw+ , showReadLaw+ ) where++import Data.Semigroup (Semigroup (..))+import Hedgehog (MonadGen, Property, forAll, property, (===))+import Numeric.Natural (Natural)++import Membrain.Memory (AnyMemory (..), Memory (..), readMemory, showMemory)++import qualified Membrain.Units as Mem++import qualified Hedgehog.Gen as Gen+import qualified Hedgehog.Range as Range+++----------------------------------------------------------------------------+-- Laws+----------------------------------------------------------------------------++{- | The semigroup associativity axiom:++@+x <> (y <> z) ≡ (x <> y) <> z+@+-}+semigroupLaw :: Property+semigroupLaw = property $ do+ x <- forAll genBitMemory+ y <- forAll genBitMemory+ z <- forAll genBitMemory+ (x <> y) <> z === x <> (y <> z)++{- | Identity law for Monoid++@+mempty <> x = x+x <> mempty = x+@+-}+monoidIdentityLaw :: Property+monoidIdentityLaw = property $ do+ x <- forAll genBitMemory++ x <> mempty === x+ mempty <> x === x++showReadLaw :: Property+showReadLaw = property $ do+ MkAnyMemory mem <- forAll genAnyMemory+ readMemory (showMemory mem) === Just mem++----------------------------------------------------------------------------+-- Generators+----------------------------------------------------------------------------++-- | Generates random natural number up to 10^20.+genNatural :: (MonadGen m) => m Natural+genNatural = Gen.integral (Range.constant 0 $ 10 ^ (20 :: Int))++genBitMemory :: MonadGen m => m (Memory Mem.Bit)+genBitMemory = Memory <$> genNatural++genAnyMemory :: MonadGen m => m AnyMemory+genAnyMemory = genNatural >>= unitChooser++-- | Returns random 'AnyMemory'.+unitChooser :: (MonadGen m) => Natural -> m AnyMemory+unitChooser n = Gen.element+ [ MkAnyMemory (Memory @Mem.Bit n)+ , MkAnyMemory (Memory @Mem.Nibble n)+ , MkAnyMemory (Memory @Mem.Byte n)++ , MkAnyMemory (Memory @Mem.Kilobyte n)+ , MkAnyMemory (Memory @Mem.Megabyte n)+ , MkAnyMemory (Memory @Mem.Gigabyte n)+ , MkAnyMemory (Memory @Mem.Terabyte n)+ , MkAnyMemory (Memory @Mem.Petabyte n)+ , MkAnyMemory (Memory @Mem.Exabyte n)+ , MkAnyMemory (Memory @Mem.Zettabyte n)+ , MkAnyMemory (Memory @Mem.Yottabyte n)++ , MkAnyMemory (Memory @Mem.Kibibyte n)+ , MkAnyMemory (Memory @Mem.Mebibyte n)+ , MkAnyMemory (Memory @Mem.Gibibyte n)+ , MkAnyMemory (Memory @Mem.Tebibyte n)+ , MkAnyMemory (Memory @Mem.Pebibyte n)+ , MkAnyMemory (Memory @Mem.Exbibyte n)+ , MkAnyMemory (Memory @Mem.Zebibyte n)+ , MkAnyMemory (Memory @Mem.Yobibyte n)+ ]
+ test/Test/Memory/TypeLevel.hs view
@@ -0,0 +1,53 @@+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE TypeOperators #-}++module Test.Memory.TypeLevel+ ( runTypeLevelTests+ ) where++import Test.TypeSpec (Is, It, TypeSpec (Valid))+import Test.TypeSpecCrazy (type ( ### ), type (-*-), type (-/-), type (~~~))++import Membrain.Units++-- | Type-check and execute all type-level tests.+runTypeLevelTests :: IO ()+runTypeLevelTests = print unitSymbolTests++unitSymbolTests ::+ "UnitSymbol"+ ###++ "Simple"+ ~~~+ It "Name Bit = b" (UnitSymbol Bit `Is` "b")+ -*- It "Name Nibble = n" (UnitSymbol Nibble `Is` "n")+ -*- It "Name Byte = B" (UnitSymbol Byte `Is` "B")++ -/-++ "Decimal"+ ~~~+ It "Name Kilobyte = kB" (UnitSymbol Kilobyte `Is` "kB")+ -*- It "Name Megabyte = MB" (UnitSymbol Megabyte `Is` "MB")+ -*- It "Name Gigabyte = GB" (UnitSymbol Gigabyte `Is` "GB")+ -*- It "Name Terabyte = TB" (UnitSymbol Terabyte `Is` "TB")+ -*- It "Name Petabyte = PB" (UnitSymbol Petabyte `Is` "PB")+ -*- It "Name Exabyte = EB" (UnitSymbol Exabyte `Is` "EB")+ -*- It "Name Zettabyte = ZB" (UnitSymbol Zettabyte `Is` "ZB")+ -*- It "Name Yottabyte = YB" (UnitSymbol Yottabyte `Is` "YB")++ -/-++ "Binary"+ ~~~+ It "Name Kibibyte = KiB" (UnitSymbol Kibibyte `Is` "KiB")+ -*- It "Name Mebibyte = MiB" (UnitSymbol Mebibyte `Is` "MiB")+ -*- It "Name Gibibyte = GiB" (UnitSymbol Gibibyte `Is` "GiB")+ -*- It "Name Tebibyte = TiB" (UnitSymbol Tebibyte `Is` "TiB")+ -*- It "Name Pebibyte = PiB" (UnitSymbol Pebibyte `Is` "PiB")+ -*- It "Name Exbibyte = EiB" (UnitSymbol Exbibyte `Is` "EiB")+ -*- It "Name Zebibyte = ZiB" (UnitSymbol Zebibyte `Is` "ZiB")+ -*- It "Name Yobibyte = YiB" (UnitSymbol Yobibyte `Is` "YiB")+unitSymbolTests = Valid
+ test/Test/Memory/ValueLevel.hs view
@@ -0,0 +1,60 @@+-- | All unit tests for runtime values and functions.++module Test.Memory.ValueLevel+ ( unitTests+ ) where++import Data.Ratio ((%))+import Test.Hspec (Spec, describe, it, shouldBe)++import qualified Membrain as Mem+++unitTests :: Spec+unitTests = describe "Membrain: Unit tests" $ do+ unitConversionSpec+ unwrappingSpec+ readMemorySpec++unitConversionSpec :: Spec+unitConversionSpec = describe "toMemory" $ do+ it "converting to the same unit does nothing" $+ Mem.byte 42 `shouldBe` Mem.toMemory @Mem.Byte (Mem.byte 42)+ it "converting to the another unit" $+ Mem.byte 1 `shouldBe` Mem.toMemory @Mem.Byte (Mem.bit 8)++unwrappingSpec :: Spec+unwrappingSpec = describe "fromMemory" $ do+ it "toBits from bits" $+ Mem.toBits (Mem.bit 42) `shouldBe` 42+ it "toBits from bytes" $+ Mem.toBits (Mem.byte 2) `shouldBe` 16+ it "toRat from bits" $+ Mem.toRat (Mem.toMemory @Mem.Byte $ Mem.bit 7) `shouldBe` (7 % 8)+ it "flooring bytes" $+ Mem.floor @Int (Mem.byte 2) `shouldBe` 2+ it "flooring bytes from bits" $+ Mem.floor @Int (Mem.toMemory @Mem.Byte $ Mem.bit 15) `shouldBe` 1++readMemorySpec :: Spec+readMemorySpec = describe "readMemory" $ do+ it "reads correct integral Byte" $+ Mem.readMemory @Mem.Byte "2B" `shouldBe` Just (Mem.byte 2)+ it "reads correct integral with '.' Byte" $+ Mem.readMemory @Mem.Byte "2.75B" `shouldBe` Just (Mem.Memory 22)+ it "doesn't read non-representable amount of Bytes" $+ Mem.readMemory @Mem.Byte "2.22B" `shouldBe` Nothing+ it "doesn't read if type and unit symbol don't match" $+ Mem.readMemory @Mem.Terabyte "42MB" `shouldBe` Nothing+ it "doesn't read if whole part is missing" $+ Mem.readMemory @Mem.Megabyte ".42MB" `shouldBe` Nothing+ it "reads correct integral Kibibyte" $+ Mem.readMemory @Mem.Kibibyte "42KiB" `shouldBe` Just (Mem.kibibyte 42)+ it "reads correct integral Kibibyte" $+ Mem.readMemory @Mem.Kibibyte "42.5KiB" `shouldBe` Just (Mem.Memory 348160)+ it "doesn't read string with letters" $+ Mem.readMemory @Mem.Megabyte "1a.42MB" `shouldBe` Nothing+ it "doesn't read string with double dots" $+ Mem.readMemory @Mem.Megabyte "1.4.2MB" `shouldBe` Nothing+ it "doesn't read string without unit" $+ Mem.readMemory @Mem.Megabyte "42" `shouldBe` Nothing