text
string |
---|
--- LICENSE ---
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--- README.md ---
# Minimal SDL binding for Mojo 🔥
Very basic native Mojo bindings to SDL2. No Python is used at runtime.
A Python script to generate different colormaps for the demo is included.
## Usage
Requires SDL installed:
#### Ubuntu
```bash
apt install libsdl2-dev
```
#### Fedora
```bash
dnf install sdl2-devel
```
#### Mac OS
```bash
brew install sdl2
```
Copy `SDL.mojo` to your project or try the Mandelbrot demo ported from [Mojo examples](https://github.com/modularml/mojo/tree/main/examples/mandelbrot.mojo)
## Demo
Run
```bash
mojo mandelbrot.mojo
```
and zoom in/out with the mouse wheel.
--- SDL.mojo ---
from sys import ffi, info
fn get_sdl_lib_path() -> StringLiteral:
if (info.os_is_linux()):
var lib_path = '/usr/lib/x86_64-linux-gnu/libSDL2.so'
try:
with open('/etc/os-release', 'r') as f:
var release = f.read()
if (release.find('Ubuntu') < 0):
lib_path = '/usr/lib64/libSDL2.so'
except:
print("Can't detect Linux version")
return lib_path
if (info.os_is_macos()):
return '/opt/homebrew/lib/libSDL2.dylib'
return ""
# SDL_PIXELFORMAT_RGBA8888 =
# SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED32, SDL_PACKEDORDER_RGBA,
# SDL_PACKEDLAYOUT_8888, 32, 4),
alias SDL_PIXELTYPE_PACKED32 = 6
alias SDL_PACKEDORDER_RGBA = 4
alias SDL_PACKEDLAYOUT_8888 = 6
fn SDL_DEFINE_PIXELFORMAT(type: Int, order: Int, layout: Int, bits: Int, bytes: Int) -> Int:
return ((1 << 28) | ((type) << 24) | ((order) << 20) | ((layout) << 16) | ((bits) << 8) | ((bytes) << 0))
alias SDL_PIXELFORMAT_RGBA8888 = SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED32,
SDL_PACKEDORDER_RGBA,
SDL_PACKEDLAYOUT_8888,
32,
4)
alias SDL_TEXTUREACCESS_TARGET = 2
@register_passable('trivial')
struct SDL_Window:
pass
@register_passable('trivial')
struct SDL_Rect:
var x: Int32
var y: Int32
var w: Int32
var h: Int32
@register_passable('trivial')
struct SDL_PixelFormat:
pass
@register_passable('trivial')
struct SDL_Renderer:
pass
@register_passable('trivial')
struct SDL_Texture:
pass
@register_passable('trivial')
struct SDL_Surface:
var flags: UInt32
var format: Pointer[SDL_PixelFormat]
var w: Int32
var h: Int32
var pitch: Int32
var pixels: Pointer[UInt32]
var userdata: Pointer[Int8]
var locked: Int32
var list_blitmap: Pointer[Int8]
var clip_rect: SDL_Rect
var map: Pointer[Int8]
var refcount: Int32
alias SDL_QUIT = 0x100
alias SDL_KEYDOWN = 0x300
alias SDL_KEYUP = 0x301
#alias SDL_
alias SDL_MOUSEMOTION = 0x400
alias SDL_MOUSEBUTTONDOWN = 0x401
alias SDL_MOUSEBUTTONUP = 0x402
alias SDL_MOUSEWHEEL = 0x403
@register_passable('trivial')
struct Keysym:
var scancode: Int32
var keycode: Int32
var mod: UInt16
var unused: UInt32
@register_passable('trivial')
struct MouseMotionEvent:
var type: UInt32
var timestamp: UInt32
var windowID: UInt32
var which: UInt32
var state: UInt32
var x: Int32
var y: Int32
var xrel: Int32
var yrel: Int32
@register_passable('trivial')
struct MouseButtonEvent:
var type: UInt32
var timestamp: UInt32
var windowID: UInt32
var which: UInt32
var button: UInt8
var state: UInt8
var clicks: UInt8
var padding1: UInt8
var x: Int32
var y: Int32
@register_passable('trivial')
struct MouseWheelEvent:
var type: UInt32
var timestamp: UInt32
var windowID: UInt32
var which: UInt32
var x: Int32
var y: Int32
var direction: UInt32
var preciseX: Float32
var preciseY: Float32
var mouseX: Int32
var mouseY: Int32
@register_passable('trivial')
struct Event:
var type: Int32
var _padding: SIMD[DType.uint8, 16]
var _padding2: Int64
var _padding3: Int64
def __init__() -> Event:
return Event { type: 0, _padding: 0, _padding2: 0, _padding3: 0 }
#fn __init__(inout self):
# self.type = 0
# self._padding = 0
# self._padding2 = 0
# self._padding3 = 0
# self._padding4 = 0
def as_keyboard(self) -> Keyevent:
return Pointer.address_of(self).bitcast[Keyevent]().load()
def as_mousemotion(self) -> MouseMotionEvent:
return Pointer.address_of(self).bitcast[MouseMotionEvent]().load()
def as_mousebutton(self) -> MouseButtonEvent:
return Pointer.address_of(self).bitcast[MouseButtonEvent]().load()
def as_mousewheel(self) -> MouseWheelEvent:
return Pointer.address_of(self).bitcast[MouseWheelEvent]().load()
#alias Event = Keyevent
@register_passable('trivial')
struct Keyevent:
var type: UInt32
var timestamp: UInt32
var windowID: UInt32
var state: UInt8
var repeat: UInt8
var padding2: UInt8
var padding3: UInt8
var keysym: Keysym
def __init__(inout self) -> Self:
#self.value = 0
self.timestamp = 0
self.windowID = 0
self.state = 0
self.repeat = 0
self.padding2 = 0
self.padding3 = 0
# SDL.h
alias c_SDL_Init = fn(w: Int32) -> Int32
alias c_SDL_Quit = fn() -> None
# SDL_video.h
alias c_SDL_CreateWindow = fn(DTypePointer[DType.int8], Int32, Int32, Int32, Int32, Int32) -> Pointer[SDL_Window]
alias c_SDL_DestroyWindow = fn(Pointer[SDL_Window]) -> None
alias c_SDL_GetWindowSurface = fn(s: Pointer[Int8]) -> Pointer[SDL_Surface]
alias c_SDL_UpdateWindowSurface = fn(s: Pointer[Int8]) -> Int32
# SDL_pixels.h
alias c_SDL_MapRGB = fn(Int32, Int32, Int32, Int32) -> UInt32
# SDL_timer.h
alias c_SDL_Delay = fn(Int32) -> UInt32
# SDL_event.h
alias c_SDL_PollEvent = fn(Pointer[Event]) -> Int32
# SDL_render.h
alias c_SDL_CreateRenderer = fn(Pointer[SDL_Window], Int32, UInt32) -> Pointer[SDL_Renderer]
alias c_SDL_CreateWindowAndRenderer = fn(Int32, Int32, UInt32, Pointer[Pointer[Int8]], Pointer[Pointer[SDL_Renderer]]) -> Int32
alias c_SDL_RenderDrawPoint = fn(Pointer[SDL_Renderer], Int32, Int32) -> Int32
alias c_SDL_RenderDrawRect = fn(r: Pointer[SDL_Renderer], rect: Pointer[SDL_Rect]) -> Int32
alias c_SDL_RenderPresent = fn(s: Pointer[SDL_Renderer]) -> Int32
alias c_SDL_RenderClear = fn(s: Pointer[SDL_Renderer]) -> Int32
alias c_SDL_SetRenderDrawColor = fn(Pointer[SDL_Renderer], UInt8, UInt8, UInt8, UInt8) -> Int32
alias SDL_BlendMode = Int
alias c_SDL_SetRenderDrawBlendMode = fn(Pointer[SDL_Renderer], SDL_BlendMode) -> Int32
alias c_SDL_SetRenderTarget = fn(r: Pointer[SDL_Renderer],
# t: Pointer[SDL_Texture]) -> Int32
t: Int64) -> Int32
alias c_SDL_RenderCopy = fn(r: Pointer[SDL_Renderer],
t: Int64, #t: Pointer[SDL_Texture],
s: Int64, d: Int64) -> Int32
#s: Pointer[SDL_Rect], d: Pointer[SDL_Rect]) -> Int32
# SDL_surface.h
alias c_SDL_FillRect = fn(Pointer[SDL_Surface], Int64, UInt32) -> Int32
# texture
alias c_SDL_CreateTexture = fn(Pointer[SDL_Renderer],
UInt32, Int32,
Int32, Int32) -> Int64 #Pointer[SDL_Texture]
alias SDL_WINDOWPOS_UNDEFINED = 0x1FFF0000
alias SDL_WINDOW_SHOWN = 0x00000004
struct SDL:
var Init: c_SDL_Init
var Quit: c_SDL_Quit
var CreateWindow: c_SDL_CreateWindow
var DestroyWindow: c_SDL_DestroyWindow
var GetWindowSurface: c_SDL_GetWindowSurface
var UpdateWindowSurface: c_SDL_UpdateWindowSurface
var CreateRenderer: c_SDL_CreateRenderer
var CreateWindowAndRenderer: c_SDL_CreateWindowAndRenderer
var RenderDrawPoint: c_SDL_RenderDrawPoint
var RenderDrawRect: c_SDL_RenderDrawRect
var SetRenderDrawColor: c_SDL_SetRenderDrawColor
var RenderPresent: c_SDL_RenderPresent
var RenderClear: c_SDL_RenderClear
var CreateTexture: c_SDL_CreateTexture
var SetRenderDrawBlendMode: c_SDL_SetRenderDrawBlendMode
var SetRenderTarget: c_SDL_SetRenderTarget
var RenderCopy: c_SDL_RenderCopy
var MapRGB: c_SDL_MapRGB
var FillRect: c_SDL_FillRect
var Delay: c_SDL_Delay
var PollEvent: c_SDL_PollEvent
fn __init__(inout self):
print("binding SDL")
var lib_path = get_sdl_lib_path()
#let SDL = ffi.DLHandle('/usr/lib64/libSDL2.so')
var SDL = ffi.DLHandle(lib_path)
self.Init = SDL.get_function[c_SDL_Init]('SDL_Init')
self.Quit = SDL.get_function[c_SDL_Quit]('SDL_Quit')
self.CreateWindow = SDL.get_function[c_SDL_CreateWindow]('SDL_CreateWindow')
self.DestroyWindow = SDL.get_function[c_SDL_DestroyWindow]('SDL_DestroyWindow')
self.GetWindowSurface = SDL.get_function[c_SDL_GetWindowSurface]('SDL_GetWindowSurface')
self.UpdateWindowSurface = SDL.get_function[c_SDL_UpdateWindowSurface]('SDL_UpdateWindowSurface')
self.CreateRenderer = SDL.get_function[c_SDL_CreateRenderer]('SDL_CreateRenderer')
self.CreateWindowAndRenderer = SDL.get_function[c_SDL_CreateWindowAndRenderer]('SDL_CreateWindowAndRenderer')
self.RenderDrawPoint = SDL.get_function[c_SDL_RenderDrawPoint]('SDL_RenderDrawPoint')
self.RenderDrawRect = SDL.get_function[c_SDL_RenderDrawRect]('SDL_RenderDrawRect')
self.SetRenderDrawColor = SDL.get_function[c_SDL_SetRenderDrawColor]('SDL_SetRenderDrawColor')
self.RenderPresent = SDL.get_function[c_SDL_RenderPresent]('SDL_RenderPresent')
self.RenderClear = SDL.get_function[c_SDL_RenderClear]('SDL_RenderClear')
self.SetRenderDrawBlendMode = SDL.get_function[c_SDL_SetRenderDrawBlendMode]('SDL_SetRenderDrawBlendMode')
self.SetRenderTarget = SDL.get_function[c_SDL_SetRenderTarget]('SDL_SetRenderTarget')
self.RenderCopy = SDL.get_function[c_SDL_RenderCopy]('SDL_RenderCopy')
self.CreateTexture = SDL.get_function[c_SDL_CreateTexture]('SDL_CreateTexture')
self.MapRGB = SDL.get_function[c_SDL_MapRGB]('SDL_MapRGB')
self.FillRect = SDL.get_function[c_SDL_FillRect]('SDL_FillRect')
self.Delay = SDL.get_function[c_SDL_Delay]('SDL_Delay')
self.PollEvent = SDL.get_function[c_SDL_PollEvent]('SDL_PollEvent')
--- cmap.mojo ---
alias vec3 = StaticTuple[3]
alias cmap = StaticTuple[256] (
vec3(0, 0, 0),
vec3(2, 0, 0),
vec3(4, 0, 0),
vec3(6, 0, 0),
vec3(8, 0, 0),
vec3(10, 0, 0),
vec3(12, 0, 0),
vec3(14, 0, 0),
vec3(16, 0, 0),
vec3(18, 0, 0),
vec3(20, 0, 0),
vec3(22, 0, 0),
vec3(24, 0, 0),
vec3(26, 0, 0),
vec3(28, 0, 0),
vec3(30, 0, 0),
vec3(32, 0, 0),
vec3(34, 0, 0),
vec3(36, 0, 0),
vec3(38, 0, 0),
vec3(40, 0, 0),
vec3(42, 0, 0),
vec3(44, 0, 0),
vec3(46, 0, 0),
vec3(48, 0, 0),
vec3(50, 0, 0),
vec3(52, 0, 0),
vec3(54, 0, 0),
vec3(56, 0, 0),
vec3(58, 0, 0),
vec3(60, 0, 0),
vec3(62, 0, 0),
vec3(64, 0, 0),
vec3(65, 0, 0),
vec3(68, 0, 0),
vec3(70, 0, 0),
vec3(72, 0, 0),
vec3(73, 0, 0),
vec3(76, 0, 0),
vec3(78, 0, 0),
vec3(80, 0, 0),
vec3(81, 0, 0),
vec3(84, 0, 0),
vec3(86, 0, 0),
vec3(88, 0, 0),
vec3(89, 0, 0),
vec3(92, 0, 0),
vec3(94, 0, 0),
vec3(96, 0, 0),
vec3(97, 0, 0),
vec3(100, 0, 0),
vec3(102, 0, 0),
vec3(104, 0, 0),
vec3(105, 0, 0),
vec3(108, 0, 0),
vec3(110, 0, 0),
vec3(112, 0, 0),
vec3(113, 0, 0),
vec3(116, 0, 0),
vec3(118, 0, 0),
vec3(120, 0, 0),
vec3(121, 0, 0),
vec3(124, 0, 0),
vec3(126, 0, 0),
vec3(128, 0, 0),
vec3(130, 2, 0),
vec3(131, 4, 0),
vec3(134, 6, 0),
vec3(136, 8, 0),
vec3(138, 10, 0),
vec3(140, 12, 0),
vec3(142, 14, 0),
vec3(144, 16, 0),
vec3(146, 18, 0),
vec3(147, 20, 0),
vec3(150, 22, 0),
vec3(152, 24, 0),
vec3(154, 26, 0),
vec3(156, 28, 0),
vec3(158, 30, 0),
vec3(160, 32, 0),
vec3(162, 34, 0),
vec3(163, 36, 0),
vec3(166, 38, 0),
vec3(168, 40, 0),
vec3(170, 42, 0),
vec3(172, 44, 0),
vec3(174, 46, 0),
vec3(176, 48, 0),
vec3(178, 50, 0),
vec3(179, 52, 0),
vec3(182, 54, 0),
vec3(184, 56, 0),
vec3(186, 58, 0),
vec3(188, 60, 0),
vec3(190, 62, 0),
vec3(192, 64, 0),
vec3(194, 66, 0),
vec3(195, 68, 0),
vec3(198, 70, 0),
vec3(200, 72, 0),
vec3(202, 74, 0),
vec3(204, 76, 0),
vec3(206, 78, 0),
vec3(208, 80, 0),
vec3(210, 82, 0),
vec3(211, 84, 0),
vec3(214, 86, 0),
vec3(216, 88, 0),
vec3(218, 90, 0),
vec3(220, 92, 0),
vec3(222, 94, 0),
vec3(224, 96, 0),
vec3(226, 98, 0),
vec3(227, 100, 0),
vec3(230, 102, 0),
vec3(232, 104, 0),
vec3(234, 106, 0),
vec3(236, 108, 0),
vec3(238, 110, 0),
vec3(240, 112, 0),
vec3(242, 114, 0),
vec3(243, 116, 0),
vec3(246, 118, 0),
vec3(248, 120, 0),
vec3(250, 122, 0),
vec3(252, 124, 0),
vec3(254, 126, 0),
vec3(255, 128, 0),
vec3(255, 130, 2),
vec3(255, 132, 4),
vec3(255, 134, 6),
vec3(255, 136, 8),
vec3(255, 138, 11),
vec3(255, 140, 13),
vec3(255, 142, 15),
vec3(255, 144, 16),
vec3(255, 146, 18),
vec3(255, 148, 20),
vec3(255, 150, 22),
vec3(255, 152, 25),
vec3(255, 154, 27),
vec3(255, 156, 29),
vec3(255, 158, 31),
vec3(255, 160, 32),
vec3(255, 162, 34),
vec3(255, 164, 36),
vec3(255, 166, 38),
vec3(255, 168, 40),
vec3(255, 170, 43),
vec3(255, 172, 45),
vec3(255, 174, 47),
vec3(255, 176, 48),
vec3(255, 178, 50),
vec3(255, 180, 52),
vec3(255, 182, 54),
vec3(255, 184, 57),
vec3(255, 186, 59),
vec3(255, 188, 61),
vec3(255, 190, 63),
vec3(255, 192, 65),
vec3(255, 194, 66),
vec3(255, 196, 68),
vec3(255, 198, 70),
vec3(255, 200, 72),
vec3(255, 202, 75),
vec3(255, 204, 77),
vec3(255, 206, 79),
vec3(255, 208, 81),
vec3(255, 210, 82),
vec3(255, 212, 84),
vec3(255, 214, 86),
vec3(255, 216, 89),
vec3(255, 218, 91),
vec3(255, 220, 93),
vec3(255, 222, 95),
vec3(255, 224, 97),
vec3(255, 226, 98),
vec3(255, 228, 100),
vec3(255, 230, 102),
vec3(255, 232, 104),
vec3(255, 234, 107),
vec3(255, 236, 109),
vec3(255, 238, 111),
vec3(255, 240, 113),
vec3(255, 242, 114),
vec3(255, 244, 116),
vec3(255, 246, 118),
vec3(255, 248, 121),
vec3(255, 250, 123),
vec3(255, 252, 125),
vec3(255, 254, 127),
vec3(255, 255, 129),
vec3(255, 255, 131),
vec3(255, 255, 132),
vec3(255, 255, 134),
vec3(255, 255, 136),
vec3(255, 255, 139),
vec3(255, 255, 141),
vec3(255, 255, 143),
vec3(255, 255, 145),
vec3(255, 255, 147),
vec3(255, 255, 148),
vec3(255, 255, 150),
vec3(255, 255, 153),
vec3(255, 255, 155),
vec3(255, 255, 157),
vec3(255, 255, 159),
vec3(255, 255, 161),
vec3(255, 255, 163),
vec3(255, 255, 164),
vec3(255, 255, 166),
vec3(255, 255, 168),
vec3(255, 255, 171),
vec3(255, 255, 173),
vec3(255, 255, 175),
vec3(255, 255, 177),
vec3(255, 255, 179),
vec3(255, 255, 180),
vec3(255, 255, 182),
vec3(255, 255, 185),
vec3(255, 255, 187),
vec3(255, 255, 189),
vec3(255, 255, 191),
vec3(255, 255, 193),
vec3(255, 255, 195),
vec3(255, 255, 196),
vec3(255, 255, 198),
vec3(255, 255, 200),
vec3(255, 255, 203),
vec3(255, 255, 205),
vec3(255, 255, 207),
vec3(255, 255, 209),
vec3(255, 255, 211),
vec3(255, 255, 212),
vec3(255, 255, 214),
vec3(255, 255, 217),
vec3(255, 255, 219),
vec3(255, 255, 221),
vec3(255, 255, 223),
vec3(255, 255, 225),
vec3(255, 255, 227),
vec3(255, 255, 228),
vec3(255, 255, 230),
vec3(255, 255, 232),
vec3(255, 255, 235),
vec3(255, 255, 237),
vec3(255, 255, 239),
vec3(255, 255, 241),
vec3(255, 255, 243),
vec3(255, 255, 244),
vec3(255, 255, 246),
vec3(255, 255, 249),
vec3(255, 255, 251),
vec3(255, 255, 253),
vec3(255, 255, 255),
)
--- gencmap.py ---
#!/usr/bin/env python3
import sys
import matplotlib as mpl
cmap_name = 'afmhot'
if len(sys.argv) > 1:
cmap_name = sys.argv[1]
cmap8bit = mpl.colormaps[cmap_name].resampled(256)
print("alias vec3 = StaticTuple[3]")
print("alias cmap = StaticTuple[256] (")
for i in range(256):
c = cmap8bit(i)
print(f'vec3({int(c[0]*255)}, {int(c[1]*255)}, {int(c[2]*255)}),')
print(')')
--- mandelbrot.mojo ---
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2023, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
import benchmark
from complex import ComplexSIMD, ComplexFloat64
from math import iota, clamp, log, pow
from python import Python
from algorithm import parallelize, vectorize
from tensor import Tensor
from utils.index import Index
from memory.unsafe import bitcast
from SDL import *
from cmap import cmap
alias float_type = DType.float64
alias simd_width = 2 * simdwidthof[float_type]()
alias width = 480
alias height = 480
alias MAX_ITERS = 500
alias MIN_X = -2.0
alias MAX_X = 0.6
alias MIN_Y = -1.5
alias MAX_Y = 1.5
@no_inline
fn mandelbrot_kernel_SIMD[
simd_width: Int
](c: ComplexSIMD[float_type, simd_width]) -> SIMD[float_type, simd_width]:
"""A vectorized implementation of the inner mandelbrot computation."""
var cx = c.re
var cy = c.im
var x = SIMD[float_type, simd_width](0)
var y = SIMD[float_type, simd_width](0)
var y2 = SIMD[float_type, simd_width](0)
var iters = SIMD[float_type, simd_width](0)
var t: SIMD[DType.bool, simd_width] = True
for i in range(MAX_ITERS):
if not t.reduce_or():
break
y2 = y * y
y = x.fma(y + y, cy)
t = x.fma(x, y2) <= 4
x = x.fma(x, cx - y2)
iters = t.select(iters + 1, iters)
return iters
fn main() raises:
var t = Tensor[float_type](height, width)
var min_x: Float64 = MIN_X
var max_x: Float64 = MAX_X
var min_y: Float64 = MIN_Y
var max_y: Float64 = MAX_Y
@parameter
@no_inline
fn worker(row: Int):
var scale_x = (max_x - min_x) / width
var scale_y = (max_y - min_y) / height
#print(scale_x)
@parameter
@no_inline
fn compute_vector[simd_width: Int](col: Int):
"""Each time we operate on a `simd_width` vector of pixels."""
var cx = min_x + (col + iota[float_type, simd_width]()) * scale_x
var cy = min_y + row * scale_y
var c = ComplexSIMD[float_type, simd_width](cx, cy)
t.data().simd_store[simd_width](
row * width + col, mandelbrot_kernel_SIMD[simd_width](c)
)
# Vectorize the call to compute_vector where call gets a chunk of pixels.
vectorize[compute_vector, simd_width, width](width)
_ = t # Make sure tensor isn't destroyed before benchmark is finished
var sdl = SDL()
var res = sdl.Init(0x00000020)
var window = sdl.CreateWindow(StringRef("Mandelbrot").data,
SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
width, height, SDL_WINDOW_SHOWN)
var renderer = sdl.CreateRenderer(window, -1, 0)
var display = sdl.CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, width, height)
_ = sdl.SetRenderTarget(renderer, display)
fn redraw(sdl: SDL, t: Tensor[float_type]) raises:
var gamma: Float64 = 0.3
var cpow_max = pow(Float64(MAX_ITERS),gamma)
_ = sdl.SetRenderTarget(renderer, display)
for y in range(t.shape()[1]):
for x in range(t.shape()[0]):
var val = t[x,y]
var cpow = pow(val, gamma)
var color = cmap[(255.0*cpow/cpow_max).to_int()]
var r = color[0]
var g = color[1]
var b = color[2]
_ = sdl.SetRenderDrawColor(renderer, r, g, b, 255)
_ = sdl.RenderDrawPoint(renderer, y, x)
_ = sdl.SetRenderTarget(renderer, 0)
_ = sdl.RenderCopy(renderer, display, 0, 0)
_ = sdl.RenderPresent(renderer)
var event = Event()
fn screen_to_world(sx: Int32, sy: Int32, inout wx: Float64, inout wy: Float64):
var fsx = sx.cast[DType.float64]()
var fsy = sy.cast[DType.float64]()
wx = (max_x - min_x) * fsx/Float64(width) + min_x
wy = (max_y - min_y) * fsy/Float64(height) + min_y
var running = True
var dirty = True
while running:
while sdl.PollEvent(Pointer[Event].address_of(event)) != 0:
if (event.type == SDL_MOUSEWHEEL):
var mwe = event.as_mousewheel()
#print(mwe.preciseX, mwe.preciseY)
var scale = (1 + mwe.preciseY.cast[DType.float64]() / 20.0)
min_x = (min_x * scale)
max_x = (max_x * scale)
min_y = (min_y * scale)
max_y = (max_y * scale)
dirty = True
if (event.type == SDL_QUIT):
running = False
break
if dirty:
parallelize[worker](height, height)
dirty = False
redraw(sdl, t)
_= sdl.Delay((1000 / 120).to_int())
_ = t
sdl.DestroyWindow(window)
sdl.Quit()
--- .github/workflows/mojopkgscript.yaml ---
name: Build and Release
# define your mojo package name here
# set the path to the directory containing the module files
env:
PACKAGE_NAME: mojopackage.mojopkg
MOJO_DIR: src
MOJO_HOME: /home/runner/.modular/pkg/packages.modular.com_mojo/bin
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
workflow_dispatch:
branches: [ main ]
jobs:
build:
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v2
- name: Install dependencies
run: |
curl https://get.modular.com | MODULAR_AUTH=${{ secrets.MODULAR_API }} sh -
modular install mojo
- name: Build
run: |
${{ env.MOJO_HOME }}/mojo package ${{ env.MOJO_DIR }} -o ${{ github.workspace }}/${{ env.PACKAGE_NAME }}
- name: Upload package
uses: actions/upload-artifact@v3
with:
name: ${{ env.PACKAGE_NAME }}
path: ${{ github.workspace }}/${{ env.PACKAGE_NAME }}
--- README.md ---
## Packaging 📦 Mojo 🔥 via GitHub Action Script
This Repository shows how to use a simple GitHub Action script for compiling a mojo directory into a package 📦.
You can find the action script here --> [Action Script](./.github/workflows/mojopkgscript.yaml).
To use this action script in your own workflow be sure to set your own GitHub secret for the Mojo API key. How to set a GitHub secret can be found [here](https://docs.github.com/en/actions/security-guides/using-secrets-in-github-actions). The variable used in the Action script for your API is 'MODULAR_API'. Be sure to use the same name or change the variable name in the script.
* Set the package name in the `PACKAGE_NAME` environment variable.
* Set your path of the directory to be packaged in the `MOJO_DIR` environment variable.
Everytime you push to the repository the action script will compile the mojo directory into a package and upload it as an artifact in the GitHub workflow. From there users can download the package and use it in hteir own code base. You can modify this script with additional actions for release deploys on the GitHub Release page.
The `testpkg.mojo` file is a simple mojo that uses the compiled package to call a function.
You can read more about packaging at the Modular documentation page found [here](https://docs.modular.com/mojo/manual/get-started/packages.html)
--- src/__init__.mojo ---
--- src/mojopkg.mojo ---
fn add(a: Int, b: Int) -> Int:
return a + b
--- testpkg.mojo ---
# This file can only executed without error after building the mojopackage
from mojopackage.mojopkg import add
fn main():
let res = add(1, 2)
print(res)
--- .github/workflows/build.yml ---
name: Build and Release
env:
PACKAGE_NAME: morrow.mojopkg
MORROW_SRC: morrow
on: workflow_dispatch
jobs:
build:
runs-on: ubuntu-22.04
steps:
- name: Check out repository code
uses: actions/checkout@v2
- name: Install dependencies
run: |
curl https://get.modular.com | MODULAR_AUTH=${{ secrets.MODULAR_AUTH }} sh -
modular auth ${{ secrets.MODULAR_AUTH }}
python3 -m venv ~/max-venv && source ~/max-venv/bin/activate
modular install max
MAX_PATH=$(modular config max.path) \
&& python3 -m pip install --find-links $MAX_PATH/wheels max-engine
MAX_PATH=$(modular config max.path) \
&& BASHRC=$( [ -f "$HOME/.bash_profile" ] && echo "$HOME/.bash_profile" || echo "$HOME/.bashrc" ) \
&& echo 'export MODULAR_HOME="'$HOME'/.modular"' >> "$BASHRC" \
&& echo 'export PATH="'$MAX_PATH'/bin:$PATH"' >> "$BASHRC" \
&& source "$BASHRC"
- name: Build
run: |
MAX_PATH=$(modular config max.path) \
&& BASHRC=$( [ -f "$HOME/.bash_profile" ] && echo "$HOME/.bash_profile" || echo "$HOME/.bashrc" ) \
&& echo 'export MODULAR_HOME="'$HOME'/.modular"' >> "$BASHRC" \
&& echo 'export PATH="'$MAX_PATH'/bin:$PATH"' >> "$BASHRC" \
&& source "$BASHRC"
mojo package ${{ env.MORROW_SRC }} -o ${{ github.workspace }}/${{ env.PACKAGE_NAME }}
- name: Upload package
uses: actions/upload-artifact@v3
with:
name: ${{ env.PACKAGE_NAME }}
path: ${{ github.workspace }}/${{ env.PACKAGE_NAME }}
--- .github/workflows/test.yml ---
name: Run Tests
on: [pull_request, push]
env:
PACKAGE_NAME: morrow.mojopkg
MORROW_SRC: morrow
jobs:
test:
runs-on: ubuntu-22.04
steps:
- name: Check out repository code
uses: actions/checkout@v2
- name: Install dependencies
run: |
curl https://get.modular.com | MODULAR_AUTH=${{ secrets.MODULAR_AUTH }} sh -
modular auth ${{ secrets.MODULAR_AUTH }}
python3 -m venv ~/max-venv && source ~/max-venv/bin/activate
modular install max
MAX_PATH=$(modular config max.path) \
&& python3 -m pip install --find-links $MAX_PATH/wheels max-engine
- name: Test
run: |
MAX_PATH=$(modular config max.path) \
&& BASHRC=$( [ -f "$HOME/.bash_profile" ] && echo "$HOME/.bash_profile" || echo "$HOME/.bashrc" ) \
&& echo 'export MODULAR_HOME="'$HOME'/.modular"' >> "$BASHRC" \
&& echo 'export PATH="'$MAX_PATH'/bin:$PATH"' >> "$BASHRC" \
&& source "$BASHRC"
mojo run test.mojo
--- .gitignore ---
.vscode
.idea
--- LICENSE ---
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--- Makefile ---
test:
mojo run test.mojo
format:
mojo format .
build:
mojo package morrow -o morrow.mojopkg
--- README.md ---
# Morrow.mojo: Human-friendly date & time for Mojo 🔥
<p align="center">
<a href="https://github.com/mojoto/morrow.mojo/actions/workflows/test.yml">
<img src="https://github.com/mojoto/morrow.mojo/actions/workflows/test.yml/badge.svg" alt="Test" />
</a>
<a href="https://github.com/mojoto/morrow.mojo/releases">
<img alt="GitHub release" src="https://img.shields.io/github/v/release/mojoto/morrow.mojo">
</a>
</p>
**Morrow** is a Mojo library that provides human-friendly method for managing, formatting, and transforming dates, times, and timestamps.
Morrow is heavily inspired by [arrow](https://github.com/arrow-py/arrow), and thanks for its elegant design.
## Features
- TimeZone-aware and UTC by default.
- Support format and parse strings.
- Support for the [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) standard.
## Preparation
You have three ways to reference this library:
- Download morrow.mojopkg from [releases](https://github.com/mojoto/morrow.mojo/releases).
- Clone this project and execute `make build` to build morrow.mojopkg.
- Directly copy the `morrow` directory of this project to your own project.
## Usage
```python
from morrow import Morrow, TimeZone
# Get local date and time.
var now = Morrow.now()
print(str(now)) # 2023-10-01T20:10:25.188957+08:00
# Get UTC date and time.
var utcnow = Morrow.utcnow()
print(str(utcnow)) # 2023-10-01T20:10:25.954638+00:00
# Get local time from POSIX timestamp.
var t = Morrow.fromtimestamp(1696089600)
print(str(t)) # 2023-10-01T00:00:00.000000+08:00
# Get UTC time from POSIX timestamp.
var utc_t = Morrow.utcfromtimestamp(1696089600)
print(str(utc_t)) # 2023-09-30T16:00:00.000000+00:00
# Get ISO format.
var m = Morrow(2023, 10, 1, 0, 0, 0, 1234)
print(m.isoformat()) # 2023-10-01T00:00:00.001234
# custom format
var m = Morrow(2023, 10, 1, 0, 0, 0, 1234)
print(m.format("YYYY-MM-DD HH:mm:ss.SSSSSS ZZ")) # 2023-10-01 00:00:00.001234 +00:00
print(m.format("dddd, DD MMM YYYY HH:mm:ss ZZZ")) # Sunday, 01 Oct 2023 00:00:00 UTC
print(m.format("YYYY[Y]MM[M]DD[D]")) # 2023Y10M01D
# Get ISO format with time zone.
var m_beijing = Morrow(2023, 10, 1, 0, 0, 0, 1234, TimeZone(28800, 'Bejing'))
print(m_beijing.isoformat(timespec="seconds")) # 2023-10-01T00:00:00+08:00
# Get time zone offset.
print(TimeZone.from_utc('UTC+08:00').offset) # 28800
# Subtract two dates.
var timedelta = Morrow(2023, 10, 2, 10, 0, 0) - Morrow(2023, 10, 1, 10, 0, 0)
print(str(timedelta)) # 1 day, 0:00:00
# Return proleptic Gregorian ordinal for the year, month and day.
var m_10_1 = Morrow(2023, 10, 1)
var ordinal = m_10_1.toordinal()
print(ordinal) # 738794
# Construct a Morrow from a proleptic Gregorian ordinal.
var m_10_1_ = Morrow.fromordinal(ordinal)
print(str(m_10_1_)) # 2023-10-01T00:00:00.000000
# Convert Morrow to python datetime
var py_dt = now.to_py()
print(py_dt.isoformat()) # 2023-10-01T20:10:25.188957
# Convert python datetime to Morrow
var m_from_py = Morrow.from_py(py_dt)
print(m_from_py) # 2023-10-01T20:10:25.188957
```
--- morrow/__init__.mojo ---
from .morrow import Morrow
from .timezone import TimeZone
from .timedelta import TimeDelta
alias __version__ = "0.4.0"
--- morrow/_libc.mojo ---
from memory.unsafe import Pointer
alias c_void = UInt8
alias c_char = UInt8
alias c_schar = Int8
alias c_uchar = UInt8
alias c_short = Int16
alias c_ushort = UInt16
alias c_int = Int32
alias c_uint = UInt32
alias c_long = Int64
alias c_ulong = UInt64
alias c_float = Float32
alias c_double = Float64
@value
@register_passable("trivial")
struct CTimeval:
var tv_sec: Int # Seconds
var tv_usec: Int # Microseconds
fn __init__(tv_sec: Int = 0, tv_usec: Int = 0) -> Self:
return Self {tv_sec: tv_sec, tv_usec: tv_usec}
@value
@register_passable("trivial")
struct CTm:
var tm_sec: Int32 # Seconds
var tm_min: Int32 # Minutes
var tm_hour: Int32 # Hour
var tm_mday: Int32 # Day of the month
var tm_mon: Int32 # Month
var tm_year: Int32 # Year minus 1900
var tm_wday: Int32 # Day of the week
var tm_yday: Int32 # Day of the year
var tm_isdst: Int32 # Daylight savings flag
var tm_gmtoff: Int64 # localtime zone offset seconds
fn __init__() -> Self:
return Self {
tm_sec: 0,
tm_min: 0,
tm_hour: 0,
tm_mday: 0,
tm_mon: 0,
tm_year: 0,
tm_wday: 0,
tm_yday: 0,
tm_isdst: 0,
tm_gmtoff: 0,
}
@always_inline
fn c_gettimeofday() -> CTimeval:
var tv = CTimeval()
var p_tv = Pointer[CTimeval].address_of(tv)
external_call["gettimeofday", NoneType, Pointer[CTimeval], Int32](p_tv, 0)
return tv
@always_inline
fn c_localtime(owned tv_sec: Int) -> CTm:
var p_tv_sec = Pointer[Int].address_of(tv_sec)
var tm = external_call["localtime", Pointer[CTm], Pointer[Int]](p_tv_sec).load()
return tm
@always_inline
fn c_strptime(time_str: String, time_format: String) -> CTm:
var tm = CTm()
var p_tm = Pointer[CTm].address_of(tm)
external_call["strptime", NoneType, Pointer[c_char], Pointer[c_char], Pointer[CTm]](
to_char_ptr(time_str), to_char_ptr(time_format), p_tm
)
return tm
@always_inline
fn c_gmtime(owned tv_sec: Int) -> CTm:
var p_tv_sec = Pointer[Int].address_of(tv_sec)
var tm = external_call["gmtime", Pointer[CTm], Pointer[Int]](p_tv_sec).load()
return tm
fn to_char_ptr(s: String) -> Pointer[c_char]:
"""Only ASCII-based strings."""
var ptr = Pointer[c_char]().alloc(len(s))
for i in range(len(s)):
ptr.store(i, ord(s[i]))
return ptr
--- morrow/_py.mojo ---
from python import Python
fn py_dt_datetime() raises -> PythonObject:
var _datetime = Python.import_module("datetime")
return _datetime.datetime
fn py_time() raises -> PythonObject:
var _time = Python.import_module("time")
return _time
--- morrow/constants.mojo ---
from utils import StaticTuple
# todo: hardcode for tmp
alias _MAX_TIMESTAMP: Int = 32503737600
alias MAX_TIMESTAMP = _MAX_TIMESTAMP
alias MAX_TIMESTAMP_MS = MAX_TIMESTAMP * 1000
alias MAX_TIMESTAMP_US = MAX_TIMESTAMP * 1_000_000
alias _DAYS_IN_MONTH = VariadicList[Int](
-1, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
)
alias _DAYS_BEFORE_MONTH = VariadicList[Int](
-1, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
) # -1 is a placeholder for indexing purposes.
alias MONTH_NAMES = StaticTuple[StringLiteral, 13](
"",
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
)
alias MONTH_ABBREVIATIONS = StaticTuple[StringLiteral, 13](
"",
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
)
alias DAY_NAMES = StaticTuple[StringLiteral, 8](
"",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday",
)
alias DAY_ABBREVIATIONS = StaticTuple[StringLiteral, 8](
"", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
)
--- morrow/formatter.mojo ---
from collections.vector import InlinedFixedVector
from utils.static_tuple import StaticTuple
from .util import rjust
from .constants import MONTH_NAMES, MONTH_ABBREVIATIONS, DAY_NAMES, DAY_ABBREVIATIONS
from .timezone import UTC_TZ
alias formatter = _Formatter()
struct _Formatter:
var _sub_chrs: InlinedFixedVector[Int, 128]
fn __init__(inout self):
self._sub_chrs = InlinedFixedVector[Int, 128](0)
for i in range(128):
self._sub_chrs[i] = 0
self._sub_chrs[_Y] = 4
self._sub_chrs[_M] = 4
self._sub_chrs[_D] = 2
self._sub_chrs[_d] = 4
self._sub_chrs[_H] = 2
self._sub_chrs[_h] = 2
self._sub_chrs[_m] = 2
self._sub_chrs[_s] = 2
self._sub_chrs[_S] = 6
self._sub_chrs[_Z] = 3
self._sub_chrs[_A] = 1
self._sub_chrs[_a] = 1
fn format(self, m: Morrow, fmt: String) raises -> String:
"""
"YYYY[abc]MM" -> repalce("YYYY") + "abc" + replace("MM")
"""
if len(fmt) == 0:
return ""
var ret: String = ""
var in_bracket = False
var start_idx = 0
for i in range(len(fmt)):
if fmt[i] == "[":
if in_bracket:
ret += "["
else:
in_bracket = True
ret += self.replace(m, fmt[start_idx:i])
start_idx = i + 1
elif fmt[i] == "]":
if in_bracket:
ret += fmt[start_idx:i]
in_bracket = False
else:
ret += self.replace(m, fmt[start_idx:i])
ret += "]"
start_idx = i + 1
if in_bracket:
ret += "["
if start_idx < len(fmt):
ret += self.replace(m, fmt[start_idx:])
return ret
fn replace(self, m: Morrow, s: String) raises -> String:
"""
split token and replace
"""
if len(s) == 0:
return ""
var ret: String = ""
var match_chr_ord = 0
var match_count = 0
for i in range(len(s)):
var c = ord(s[i])
if 0 < c < 128 and self._sub_chrs[c] > 0:
if c == match_chr_ord:
match_count += 1
else:
ret += self.replace_token(m, match_chr_ord, match_count)
match_chr_ord = c
match_count = 1
if match_count == self._sub_chrs[c]:
ret += self.replace_token(m, match_chr_ord, match_count)
match_chr_ord = 0
else:
if match_chr_ord > 0:
ret += self.replace_token(m, match_chr_ord, match_count)
match_chr_ord = 0
ret += s[i]
if match_chr_ord > 0:
ret += self.replace_token(m, match_chr_ord, match_count)
return ret
fn replace_token(self, m: Morrow, token: Int, token_count: Int) raises -> String:
if token == _Y:
if token_count == 1:
return "Y"
if token_count == 2:
return rjust(m.year, 4, "0")[2:4]
if token_count == 4:
return rjust(m.year, 4, "0")
elif token == _M:
if token_count == 1:
return String(m.month)
if token_count == 2:
return rjust(m.month, 2, "0")
if token_count == 3:
return String(MONTH_ABBREVIATIONS[m.month])
if token_count == 4:
return String(MONTH_NAMES[m.month])
elif token == _D:
if token_count == 1:
return String(m.day)
if token_count == 2:
return rjust(m.day, 2, "0")
elif token == _H:
if token_count == 1:
return String(m.hour)
if token_count == 2:
return rjust(m.hour, 2, "0")
elif token == _h:
var h_12 = m.hour
if m.hour > 12:
h_12 -= 12
if token_count == 1:
return String(h_12)
if token_count == 2:
return rjust(h_12, 2, "0")
elif token == _m:
if token_count == 1:
return String(m.minute)
if token_count == 2:
return rjust(m.minute, 2, "0")
elif token == _s:
if token_count == 1:
return String(m.second)
if token_count == 2:
return rjust(m.second, 2, "0")
elif token == _S:
if token_count == 1:
return String(m.microsecond // 100000)
if token_count == 2:
return rjust(m.microsecond // 10000, 2, "0")
if token_count == 3:
return rjust(m.microsecond // 1000, 3, "0")
if token_count == 4:
return rjust(m.microsecond // 100, 4, "0")
if token_count == 5:
return rjust(m.microsecond // 10, 5, "0")
if token_count == 6:
return rjust(m.microsecond, 6, "0")
elif token == _d:
if token_count == 1:
return String(m.isoweekday())
if token_count == 3:
return String(DAY_ABBREVIATIONS[m.isoweekday()])
if token_count == 4:
return String(DAY_NAMES[m.isoweekday()])
elif token == _Z:
if token_count == 3:
return UTC_TZ.name if m.tz.is_none() else m.tz.name
var separator = "" if token_count == 1 else ":"
if m.tz.is_none():
return UTC_TZ.format(separator)
else:
return m.tz.format(separator)
elif token == _a:
return "am" if m.hour < 12 else "pm"
elif token == _A:
return "AM" if m.hour < 12 else "PM"
return ""
alias _Y = ord("Y")
alias _M = ord("M")
alias _D = ord("D")
alias _d = ord("d")
alias _H = ord("H")
alias _h = ord("h")
alias _m = ord("m")
alias _s = ord("s")
alias _S = ord("S")
alias _X = ord("X")
alias _x = ord("x")
alias _Z = ord("Z")
alias _A = ord("A")
alias _a = ord("a")
--- morrow/morrow.mojo ---
from ._py import py_dt_datetime
from .util import normalize_timestamp, rjust, _ymd2ord, _days_before_year
from ._libc import c_gettimeofday, c_localtime, c_gmtime, c_strptime
from ._libc import CTimeval, CTm
from .timezone import TimeZone
from .timedelta import TimeDelta
from .formatter import formatter
from .constants import _DAYS_BEFORE_MONTH, _DAYS_IN_MONTH
from python.object import PythonObject
from python import Python
alias _DI400Y = 146097 # number of days in 400 years
alias _DI100Y = 36524 # " " " " 100 "
alias _DI4Y = 1461 # " " " " 4 "
@value
struct Morrow(StringableRaising):
var year: Int
var month: Int
var day: Int
var hour: Int
var minute: Int
var second: Int
var microsecond: Int
var tz: TimeZone
fn __init__(
inout self,
year: Int,
month: Int,
day: Int,
hour: Int = 0,
minute: Int = 0,
second: Int = 0,
microsecond: Int = 0,
tz: TimeZone = TimeZone.none(),
) raises:
self.year = year
self.month = month
self.day = day
self.hour = hour
self.minute = minute
self.second = second
self.microsecond = microsecond
self.tz = tz
@staticmethod
fn now() raises -> Self:
var t = c_gettimeofday()
return Self._fromtimestamp(t, False)
@staticmethod
fn utcnow() raises -> Self:
var t = c_gettimeofday()
return Self._fromtimestamp(t, True)
@staticmethod
fn _fromtimestamp(t: CTimeval, utc: Bool) raises -> Self:
var tm: CTm
var tz: TimeZone
if utc:
tm = c_gmtime(t.tv_sec)
tz = TimeZone(0, "UTC")
else:
tm = c_localtime(t.tv_sec)
tz = TimeZone(int(tm.tm_gmtoff), "local")
var result = Self(
int(tm.tm_year) + 1900,
int(tm.tm_mon) + 1,
int(tm.tm_mday),
int(tm.tm_hour),
int(tm.tm_min),
int(tm.tm_sec),
t.tv_usec,
tz,
)
return result
@staticmethod
fn fromtimestamp(timestamp: Float64) raises -> Self:
var timestamp_ = normalize_timestamp(timestamp)
var t = CTimeval(int(timestamp_))
return Self._fromtimestamp(t, False)
@staticmethod
fn utcfromtimestamp(timestamp: Float64) raises -> Self:
var timestamp_ = normalize_timestamp(timestamp)
var t = CTimeval(int(timestamp_))
return Self._fromtimestamp(t, True)
@staticmethod
fn strptime(
date_str: String, fmt: String, tzinfo: TimeZone = TimeZone.none()
) raises -> Self:
"""
Create a Morrow instance from a date string and format,
in the style of ``datetime.strptime``. Optionally replaces the parsed TimeZone.
Usage::
>>> Morrow.strptime('20-01-2019 15:49:10', '%d-%m-%Y %H:%M:%S')
<Morrow [2019-01-20T15:49:10+00:00]>
"""
var tm = c_strptime(date_str, fmt)
var tz = TimeZone(int(tm.tm_gmtoff)) if tzinfo.is_none() else tzinfo
return Self(
int(tm.tm_year) + 1900,
int(tm.tm_mon) + 1,
int(tm.tm_mday),
int(tm.tm_hour),
int(tm.tm_min),
int(tm.tm_sec),
0,
tz,
)
@staticmethod
fn strptime(date_str: String, fmt: String, tz_str: String) raises -> Self:
"""
Create a Morrow instance by time_zone_string with utc format.
Usage::
>>> Morrow.strptime('20-01-2019 15:49:10', '%d-%m-%Y %H:%M:%S', '+08:00')
<Morrow [2019-01-20T15:49:10+08:00]>
"""
var tzinfo = TimeZone.from_utc(tz_str)
return Self.strptime(date_str, fmt, tzinfo)
fn format(self, fmt: String = "YYYY-MM-DD HH:mm:ss ZZ") raises -> String:
"""Returns a string representation of the `Morrow`
formatted according to the provided format string.
:param fmt: the format string.
Usage::
>>> var m = Morrow.now()
>>> m.format('YYYY-MM-DD HH:mm:ss ZZ')
'2013-05-09 03:56:47 -00:00'
>>> m.format('MMMM DD, YYYY')
'May 09, 2013'
>>> m.format()
'2013-05-09 03:56:47 -00:00'
"""
return formatter.format(self, fmt)
fn isoformat(
self, sep: String = "T", timespec: StringLiteral = "auto"
) raises -> String:
"""Return the time formatted according to ISO.
The full format looks like 'YYYY-MM-DD HH:MM:SS.mmmmmm'.
If self.tzinfo is not None, the UTC offset is also attached, giving
giving a full format of 'YYYY-MM-DD HH:MM:SS.mmmmmm+HH:MM'.
Optional argument sep specifies the separator between date and
time, default 'T'.
The optional argument timespec specifies the number of additional
terms of the time to include. Valid options are 'auto', 'hours',
'minutes', 'seconds', 'milliseconds' and 'microseconds'.
"""
var date_str = (
rjust(self.year, 4, "0")
+ "-"
+ rjust(self.month, 2, "0")
+ "-"
+ rjust(self.day, 2, "0")
)
var time_str = String("")
if timespec == "auto" or timespec == "microseconds":
time_str = (
rjust(self.hour, 2, "0")
+ ":"
+ rjust(self.minute, 2, "0")
+ ":"
+ rjust(self.second, 2, "0")
+ "."
+ rjust(self.microsecond, 6, "0")
)
elif timespec == "milliseconds":
time_str = (
rjust(self.hour, 2, "0")
+ ":"
+ rjust(self.minute, 2, "0")
+ ":"
+ rjust(self.second, 2, "0")
+ "."
+ rjust(self.microsecond // 1000, 3, "0")
)
elif timespec == "seconds":
time_str = (
rjust(self.hour, 2, "0")
+ ":"
+ rjust(self.minute, 2, "0")
+ ":"
+ rjust(self.second, 2, "0")
)
elif timespec == "minutes":
time_str = rjust(self.hour, 2, "0") + ":" + rjust(self.minute, 2, "0")
elif timespec == "hours":
time_str = rjust(self.hour, 2, "0")
else:
raise Error()
if self.tz.is_none():
return sep.join(date_str, time_str)
else:
return sep.join(date_str, time_str) + self.tz.format()
fn toordinal(self) raises -> Int:
"""Return proleptic Gregorian ordinal for the year, month and day.
January 1 of year 1 is day 1. Only the year, month and day values
contribute to the result.
"""
return _ymd2ord(self.year, self.month, self.day)
@staticmethod
fn fromordinal(ordinal: Int) raises -> Self:
"""Construct a Morrow from a proleptic Gregorian ordinal.
January 1 of year 1 is day 1. Only the year, month and day are
non-zero in the result.
"""
# n is a 1-based index, starting at 1-Jan-1. The pattern of leap years
# repeats exactly every 400 years. The basic strategy is to find the
# closest 400-year boundary at or before n, then work with the offset
# from that boundary to n. Life is much clearer if we subtract 1 from
# n first -- then the values of n at 400-year boundaries are exactly
# those divisible by _DI400Y:
#
# D M Y n n-1
# -- --- ---- ---------- ----------------
# 31 Dec -400 -_DI400Y -_DI400Y -1
# 1 Jan -399 -_DI400Y +1 -_DI400Y 400-year boundary
# ...
# 30 Dec 000 -1 -2
# 31 Dec 000 0 -1
# 1 Jan 001 1 0 400-year boundary
# 2 Jan 001 2 1
# 3 Jan 001 3 2
# ...
# 31 Dec 400 _DI400Y _DI400Y -1
# 1 Jan 401 _DI400Y +1 _DI400Y 400-year boundary
var n = ordinal
n -= 1
var n400 = n // _DI400Y
n = n % _DI400Y
var year = n400 * 400 + 1 # ..., -399, 1, 401, ...
# Now n is the (non-negative) offset, in days, from January 1 of year, to
# the desired date. Now compute how many 100-year cycles precede n.
# Note that it's possible for n100 to equal 4! In that case 4 full
# 100-year cycles precede the desired day, which implies the desired
# day is December 31 at the end of a 400-year cycle.
var n100 = n // _DI100Y
n = n % _DI100Y
# Now compute how many 4-year cycles precede it.
var n4 = n // _DI4Y
n = n % _DI4Y
# And now how many single years. Again n1 can be 4, and again meaning
# that the desired day is December 31 at the end of the 4-year cycle.
var n1 = n // 365
n = n % 365
year += n100 * 100 + n4 * 4 + n1
if n1 == 4 or n100 == 4:
return Self(year - 1, 12, 31)
# Now the year is correct, and n is the offset from January 1. We find
# the month via an estimate that's either exact or one too large.
var leapyear = n1 == 3 and (n4 != 24 or n100 == 3)
var month = (n + 50) >> 5
var preceding: Int
if month > 2 and leapyear:
preceding = _DAYS_BEFORE_MONTH[month] + 1
else:
preceding = _DAYS_BEFORE_MONTH[month]
if preceding > n: # estimate is too large
month -= 1
if month == 2 and leapyear:
preceding -= _DAYS_BEFORE_MONTH[month] + 1
else:
preceding -= _DAYS_BEFORE_MONTH[month]
n -= preceding
# Now the year and month are correct, and n is the offset from the
# start of that month: we're done!
return Self(year, month, n + 1)
fn isoweekday(self) raises -> Int:
# "Return day of the week, where Monday == 1 ... Sunday == 7."
# 1-Jan-0001 is a Monday
return self.toordinal() % 7 or 7
fn __str__(self) raises -> String:
return self.isoformat()
fn __sub__(self, other: Self) raises -> TimeDelta:
var days1 = self.toordinal()
var days2 = other.toordinal()
var secs1 = self.second + self.minute * 60 + self.hour * 3600
var secs2 = other.second + other.minute * 60 + other.hour * 3600
var base = TimeDelta(
days1 - days2, secs1 - secs2, self.microsecond - other.microsecond
)
return base
fn to_py(self) raises -> PythonObject:
# todo: add tz later
var dateimte = Python.import_module("datetime")
return dateimte.datetime(
self.year,
self.month,
self.day,
self.hour,
self.minute,
self.second,
self.microsecond,
)
@staticmethod
fn from_py(py_datetime: PythonObject) raises -> Morrow:
# Python.is_type not working, use __class__.__name__ instead
if py_datetime.__class__.__name__ == "datetime":
return Morrow(
int(py_datetime.year),
int(py_datetime.month),
int(py_datetime.day),
int(py_datetime.hour),
int(py_datetime.minute),
int(py_datetime.second),
int(py_datetime.second),
)
elif py_datetime.__class__.__name__ == "date":
return Morrow(
int(py_datetime.year),
int(py_datetime.month),
int(py_datetime.day),
)
else:
raise Error(
"invalid python object, only support py builtin datetime or date"
)
--- morrow/timedelta.mojo ---
from .util import rjust
alias SECONDS_OF_DAY = 24 * 3600
struct TimeDelta(Stringable):
var days: Int
var seconds: Int
var microseconds: Int
fn __init__(
inout self,
days: Int = 0,
seconds: Int = 0,
microseconds: Int = 0,
milliseconds: Int = 0,
minutes: Int = 0,
hours: Int = 0,
weeks: Int = 0,
):
self.days = 0
self.seconds = 0
self.microseconds = 0
var days_ = days
var seconds_ = seconds
var microseconds_ = microseconds
# Normalize everything to days, seconds, microseconds.
days_ += weeks * 7
seconds_ += minutes * 60 + hours * 3600
microseconds_ += milliseconds * 1000
self.days = days_
days_ = seconds_ // SECONDS_OF_DAY
seconds_ = seconds_ % SECONDS_OF_DAY
self.days += days_
self.seconds += seconds_
seconds_ = microseconds_ // 1000000
microseconds_ = microseconds_ % 1000000
days_ = seconds_ // SECONDS_OF_DAY
seconds_ = seconds_ % SECONDS_OF_DAY
self.days += days_
self.seconds += seconds_
seconds_ = microseconds_ // 1000000
self.microseconds = microseconds_ % 1000000
self.seconds += seconds_
days_ = self.seconds // SECONDS_OF_DAY
self.seconds = self.seconds % SECONDS_OF_DAY
self.days += days_
fn __copyinit__(inout self, other: Self):
self.days = other.days
self.seconds = other.seconds
self.microseconds = other.microseconds
fn __str__(self) -> String:
var mm = self.seconds // 60
var ss = self.seconds % 60
var hh = mm // 60
mm = mm % 60
var s = String(hh) + ":" + rjust(mm, 2, "0") + ":" + rjust(ss, 2, "0")
if self.days:
if abs(self.days) != 1:
s = String(self.days) + " days, " + s
else:
s = String(self.days) + " day, " + s
if self.microseconds:
s = s + rjust(self.microseconds, 6, "0")
return s
fn total_seconds(self) -> Float64:
"""Total seconds in the duration."""
return (
(self.days * 86400 + self.seconds) * 10**6 + self.microseconds
) / 10**6
@always_inline
fn __add__(self, other: Self) -> Self:
return Self(
self.days + other.days,
self.seconds + other.seconds,
self.microseconds + other.microseconds,
)
fn __radd__(self, other: Self) -> Self:
return self.__add__(other)
fn __sub__(self, other: Self) -> Self:
return Self(
self.days - other.days,
self.seconds - other.seconds,
self.microseconds - other.microseconds,
)
fn __rsub__(self, other: Self) -> Self:
return Self(
other.days - self.days,
other.seconds - self.seconds,
other.microseconds - self.microseconds,
)
fn __neg__(self) -> Self:
return Self(-self.days, -self.seconds, -self.microseconds)
fn __pos__(self) -> Self:
return self
def __abs__(self) -> Self:
if self.days < 0:
return -self
else:
return self
@always_inline
fn __mul__(self, other: Int) -> Self:
return Self(
self.days * other,
self.seconds * other,
self.microseconds * other,
)
fn __rmul__(self, other: Int) -> Self:
return self.__mul__(other)
fn _to_microseconds(self) -> Int:
return (self.days * SECONDS_OF_DAY + self.seconds) * 1000000 + self.microseconds
fn __mod__(self, other: Self) -> Self:
var r = self._to_microseconds() % other._to_microseconds()
return Self(0, 0, r)
fn __eq__(self, other: Self) -> Bool:
return (
self.days == other.days
and self.seconds == other.seconds
and self.microseconds == other.microseconds
)
@always_inline
fn __le__(self, other: Self) -> Bool:
if self.days < other.days:
return True
elif self.days == other.days:
if self.seconds < other.seconds:
return True
elif (
self.seconds == other.seconds
and self.microseconds <= other.microseconds
):
return True
return False
@always_inline
fn __lt__(self, other: Self) -> Bool:
if self.days < other.days:
return True
elif self.days == other.days:
if self.seconds < other.seconds:
return True
elif (
self.seconds == other.seconds and self.microseconds < other.microseconds
):
return True
return False
fn __ge__(self, other: Self) -> Bool:
return not self.__lt__(other)
fn __gt__(self, other: Self) -> Bool:
return not self.__le__(other)
fn __bool__(self) -> Bool:
return self.days != 0 or self.seconds != 0 or self.microseconds != 0
alias Min = TimeDelta(-99999999)
alias Max = TimeDelta(days=99999999)
alias Resolution = TimeDelta(microseconds=1)
--- morrow/timezone.mojo ---
from .util import rjust
from ._libc import c_localtime
alias UTC_TZ = TimeZone(0, "UTC")
@value
struct TimeZone(Stringable):
var offset: Int
var name: String
fn __init__(inout self, offset: Int, name: String = ""):
self.offset = offset
self.name = name
fn __str__(self) -> String:
return self.name
fn is_none(self) -> Bool:
return self.name == "None"
@staticmethod
fn none() -> TimeZone:
return TimeZone(0, "None")
@staticmethod
fn local() -> TimeZone:
var local_t = c_localtime(0)
return TimeZone(local_t.tm_gmtoff.to_int(), "local")
@staticmethod
fn from_utc(utc_str: String) raises -> TimeZone:
if len(utc_str) == 0:
raise Error("utc_str is empty")
if utc_str == "utc" or utc_str == "UTC" or utc_str == "Z":
return TimeZone(0, "utc")
var p = 3 if len(utc_str) > 3 and utc_str[0:3] == "UTC" else 0
var sign = -1 if utc_str[p] == "-" else 1
if utc_str[p] == "+" or utc_str[p] == "-":
p += 1
if (
len(utc_str) < p + 2
or not isdigit(ord(utc_str[p]))
or not isdigit(ord(utc_str[p + 1]))
):
raise Error("utc_str format is invalid")
var hours: Int = atol(utc_str[p : p + 2])
p += 2
var minutes: Int
if len(utc_str) <= p:
minutes = 0
elif len(utc_str) == p + 3 and utc_str[p] == ":":
minutes = atol(utc_str[p + 1 : p + 3])
elif len(utc_str) == p + 2 and isdigit(ord(utc_str[p])):
minutes = atol(utc_str[p : p + 2])
else:
minutes = 0
raise Error("utc_str format is invalid")
var offset: Int = sign * (hours * 3600 + minutes * 60)
return TimeZone(offset)
fn format(self, sep: String = ":") -> String:
var sign: String
var offset_abs: Int
if self.offset < 0:
sign = "-"
offset_abs = -self.offset
else:
sign = "+"
offset_abs = self.offset
var hh = offset_abs // 3600
var mm = offset_abs % 3600
return sign + rjust(hh, 2, "0") + sep + rjust(mm, 2, "0")
--- morrow/util.mojo ---
from collections.vector import DynamicVector
from .constants import MAX_TIMESTAMP, MAX_TIMESTAMP_MS, MAX_TIMESTAMP_US
from .constants import _DAYS_IN_MONTH, _DAYS_BEFORE_MONTH
fn _is_leap(year: Int) -> Bool:
"year -> 1 if leap year, else 0."
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
def _days_before_year(year: Int) -> Int:
"year -> number of days before January 1st of year."
var y = year - 1
return y * 365 + y // 4 - y // 100 + y // 400
def _days_in_month(year: Int, month: Int) -> Int:
"year, month -> number of days in that month in that year."
if month == 2 and _is_leap(year):
return 29
return _DAYS_IN_MONTH[month]
def _days_before_month(year: Int, month: Int) -> Int:
"year, month -> number of days in year preceding first day of month."
if month > 2 and _is_leap(year):
return _DAYS_BEFORE_MONTH[month] + 1
return _DAYS_BEFORE_MONTH[month]
@always_inline
def _ymd2ord(year: Int, month: Int, day: Int) -> Int:
"year, month, day -> ordinal, considering 01-Jan-0001 as day 1."
dim = _days_in_month(year, month)
return _days_before_year(year) + _days_before_month(year, month) + day
def normalize_timestamp(timestamp: Float64) -> Float64:
"""Normalize millisecond and microsecond timestamps into normal timestamps."""
if timestamp > MAX_TIMESTAMP:
if timestamp < MAX_TIMESTAMP_MS:
timestamp /= 1000
elif timestamp < MAX_TIMESTAMP_US:
timestamp /= 1_000_000
else:
raise Error(
"The specified timestamp " + String(timestamp) + "is too large."
)
return timestamp
fn _repeat_string(string: String, n: Int) -> String:
var result: String = ""
for _ in range(n):
result += string
return result
fn rjust(string: String, width: Int, fillchar: String = " ") -> String:
var extra = width - len(string)
return _repeat_string(fillchar, extra) + string
fn rjust(string: Int, width: Int, fillchar: String = " ") -> String:
return rjust(String(string), width, fillchar)
--- test.mojo ---
from testing import assert_equal, assert_true
from morrow._libc import c_gettimeofday
from morrow._py import py_dt_datetime, py_time
from morrow import Morrow
from morrow import TimeZone
from morrow import TimeDelta
def assert_datetime_equal(dt: Morrow, py_dt: PythonObject):
assert_true(
dt.year == int(py_dt.year)
and dt.month == int(py_dt.month)
and dt.hour == int(py_dt.hour)
and dt.minute == int(py_dt.minute)
and dt.second == int(py_dt.second),
"dt: " + str(dt) + " is not equal to py_dt: " + str(py_dt),
)
def test_now():
print("Running test_now()")
var result = Morrow.now()
assert_datetime_equal(result, py_dt_datetime().now())
def test_utcnow():
print("Running test_utcnow()")
var result = Morrow.utcnow()
assert_datetime_equal(result, py_dt_datetime().utcnow())
def test_fromtimestamp():
print("Running test_fromtimestamp()")
var t = c_gettimeofday()
var result = Morrow.fromtimestamp(t.tv_sec)
assert_datetime_equal(result, py_dt_datetime().now())
def test_utcfromtimestamp():
print("Running test_utcfromtimestamp()")
var t = c_gettimeofday()
var result = Morrow.utcfromtimestamp(t.tv_sec)
assert_datetime_equal(result, py_dt_datetime().utcnow())
def test_iso_format():
print("Running test_iso_format()")
var d0 = Morrow(2023, 10, 1, 0, 0, 0, 1234)
assert_equal(d0.isoformat(), "2023-10-01T00:00:00.001234")
assert_equal(d0.isoformat(timespec="seconds"), "2023-10-01T00:00:00")
assert_equal(d0.isoformat(timespec="milliseconds"), "2023-10-01T00:00:00.001")
# with TimeZone
var d1 = Morrow(2023, 10, 1, 0, 0, 0, 1234, TimeZone(28800, "Beijing"))
assert_equal(d1.isoformat(timespec="seconds"), "2023-10-01T00:00:00+08:00")
def test_time_zone():
print("Running test_time_zone()")
assert_equal(TimeZone.from_utc("UTC+0800").offset, 28800)
assert_equal(TimeZone.from_utc("UTC+08:00").offset, 28800)
assert_equal(TimeZone.from_utc("UTC08:00").offset, 28800)
assert_equal(TimeZone.from_utc("UTC0800").offset, 28800)
assert_equal(TimeZone.from_utc("+08:00").offset, 28800)
assert_equal(TimeZone.from_utc("+0800").offset, 28800)
assert_equal(TimeZone.from_utc("08").offset, 28800)
def test_strptime():
print("Running test_strptime()")
m = Morrow.strptime("20-01-2023 15:49:10", "%d-%m-%Y %H:%M:%S", TimeZone.none())
assert_equal(str(m), "2023-01-20T15:49:10.000000+00:00")
m = Morrow.strptime("2023-10-18 15:49:10 +0800", "%Y-%m-%d %H:%M:%S %z")
assert_equal(str(m), "2023-10-18T15:49:10.000000+08:00")
m = Morrow.strptime("2023-10-18 15:49:10", "%Y-%m-%d %H:%M:%S", "+09:00")
assert_equal(str(m), "2023-10-18T15:49:10.000000+09:00")
def test_ordinal():
print("Running test_ordinal()")
m = Morrow(2023, 10, 1)
o = m.toordinal()
assert_equal(o, 738794)
m2 = Morrow.fromordinal(o)
assert_equal(m2.year, 2023)
assert_equal(m.month, 10)
assert_equal(m.day, 1)
def test_sub():
print("Running test_sub()")
var result = Morrow(2023, 10, 1, 10, 0, 0, 1) - Morrow(2023, 10, 1, 10, 0, 0)
assert_equal(result.microseconds, 1)
assert_equal(str(result), "0:00:00000001")
result = Morrow(2023, 10, 1, 10, 0, 1) - Morrow(2023, 10, 1, 10, 0, 0)
assert_equal(result.seconds, 1)
assert_equal(str(result), "0:00:01")
result = Morrow(2023, 10, 1, 10, 1, 0) - Morrow(2023, 10, 1, 10, 0, 0)
assert_equal(result.seconds, 60)
assert_equal(str(result), "0:01:00")
result = Morrow(2023, 10, 2, 10, 0, 0) - Morrow(2023, 10, 1, 10, 0, 0)
assert_equal(result.days, 1)
assert_equal(str(result), "1 day, 0:00:00")
result = Morrow(2023, 10, 3, 10, 1, 1) - Morrow(2023, 10, 1, 10, 0, 0)
assert_equal(result.days, 2)
assert_equal(str(result), "2 days, 0:01:01")
def test_timedelta():
print("Running test_timedelta()")
assert_equal(TimeDelta(3, 2, 100).total_seconds(), 259202.0001)
assert_true(
TimeDelta(2, 1, 50).__add__(TimeDelta(1, 1, 50)).__eq__(TimeDelta(3, 2, 100))
)
assert_true(
TimeDelta(3, 2, 100).__sub__(TimeDelta(2, 1, 50)).__eq__(TimeDelta(1, 1, 50))
)
assert_true(TimeDelta(3, 2, 100).__neg__().__eq__(TimeDelta(-3, -2, -100)))
assert_true(TimeDelta(-3, -2, -100).__abs__().__eq__(TimeDelta(3, 2, 100)))
assert_true(TimeDelta(1, 1, 50).__le__(TimeDelta(1, 1, 51)))
assert_true(TimeDelta(1, 1, 50).__le__(TimeDelta(1, 1, 50)))
assert_true(TimeDelta(1, 1, 50).__lt__(TimeDelta(1, 1, 51)))
assert_true(not TimeDelta(1, 1, 50).__lt__(TimeDelta(1, 1, 50)))
assert_true(TimeDelta(1, 1, 50).__ge__(TimeDelta(1, 1, 50)))
assert_true(TimeDelta(1, 1, 50).__ge__(TimeDelta(1, 1, 49)))
assert_true(not TimeDelta(1, 1, 50).__gt__(TimeDelta(1, 1, 50)))
assert_true(TimeDelta(1, 1, 50).__gt__(TimeDelta(1, 1, 49)))
assert_equal(
str(
TimeDelta(
weeks=100,
days=100,
hours=100,
minutes=100,
seconds=100,
microseconds=10000000,
milliseconds=10000000000,
)
),
"919 days, 23:28:30",
)
def test_from_to_py():
print("Running test_from_to_py()")
m = Morrow.now()
dt = m.to_py()
assert_datetime_equal(m, dt)
m2 = Morrow.from_py(dt)
assert_datetime_equal(m2, dt)
def test_format():
print("Running test_format()")
var m = Morrow(2024, 2, 1, 3, 4, 5, 123456)
assert_equal(
m.format("YYYY-MM-DD HH:mm:ss.SSS ZZ"), "2024-02-01 03:04:05.123 +00:00"
)
assert_equal(m.format("Y-YY-YYY-YYYY M-MM D-DD"), "Y-24--2024 2-02 1-01")
assert_equal(m.format("H-HH-h-hh m-mm s-ss"), "3-03-3-03 4-04 5-05")
assert_equal(m.format("S-SS-SSS-SSSS-SSSSS-SSSSSS"), "1-12-123-1234-12345-123456")
assert_equal(m.format("d-dd-ddd-dddd"), "4--Thu-Thursday")
assert_equal(m.format("YYYY[Y] [[]MM[]][M]"), "2024Y [02]M")
def main():
test_now()
test_utcnow()
test_fromtimestamp()
test_utcfromtimestamp()
test_iso_format()
test_sub()
test_time_zone()
test_strptime()
test_timedelta()
test_from_to_py()
test_format()
--- .gitignore ---
.DS_Store
--- LICENSE ---
MIT License
Copyright (c) 2023 Lukas Hermann
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
--- README.md ---
# Mojo Shims
These are a collection of random utils I've written for use in my Mojo projects. Most are ported from Zig's standard library. Some of them are have quirks due to bugs in the language, and others due to my lack of testing. Nothing here is production code, and will probably break frequently as new language changes crop up.
--- __init__.mojo ---
--- bitcast/__init__.mojo ---
from math.bit import bswap
from sys.info import is_little_endian, sizeof
@always_inline
fn read_simd_native[
T: DType
](owned bytes: SIMD[DType.uint8, sizeof[SIMD[T, 1]]()]) -> SIMD[T, 1]:
let ptr = Pointer.address_of(bytes).bitcast[SIMD[T, 1]]()
return ptr.load()
@always_inline
fn read_simd_foreign[
T: DType
](owned bytes: SIMD[DType.uint8, sizeof[SIMD[T, 1]]()]) -> SIMD[T, 1]:
return bswap[T, 1](read_simd_native[T](bytes))
@always_inline
fn from_le_bytes[
T: DType
](owned bytes: SIMD[DType.uint8, sizeof[SIMD[T, 1]]()]) -> SIMD[T, 1]:
@parameter
if is_little_endian():
return read_simd_native[T](bytes)
else:
return read_simd_foreign[T](bytes)
@always_inline
fn from_be_bytes[
T: DType, N: Int
](owned bytes: SIMD[DType.uint8, sizeof[SIMD[T, 1]]()]) -> SIMD[T, 1]:
@parameter
if is_little_endian():
return read_simd_foreign[T](bytes)
else:
return read_simd_native[T](bytes)
@always_inline
fn write_simd_native[
T: DType
](owned value: SIMD[T, 1]) -> SIMD[DType.uint8, sizeof[SIMD[T, 1]]()]:
let ptr = DTypePointer[T](Pointer.address_of[SIMD[T, 1]](value)).bitcast[
DType.uint8
]()
return ptr.simd_load[sizeof[SIMD[T, 1]]()](0)
@always_inline
fn write_simd_foreign[
T: DType
](owned value: SIMD[T, 1]) -> SIMD[DType.uint8, sizeof[SIMD[T, 1]]()]:
return bswap[DType.uint8, sizeof[SIMD[T, 1]]()](write_simd_native[T](value))
@always_inline
fn to_le_bytes[
T: DType
](owned value: SIMD[T, 1]) -> SIMD[DType.uint8, sizeof[SIMD[T, 1]]()]:
@parameter
if is_little_endian():
return write_simd_native[T](value)
else:
return write_simd_foreign[T](value)
@always_inline
fn to_be_bytes[
T: DType
](owned value: SIMD[T, 1]) -> SIMD[DType.uint8, sizeof[SIMD[T, 1]]()]:
@parameter
if is_little_endian():
return write_simd_foreign[T](value)
else:
return write_simd_native[T](value)
--- experiments/read_dir.mojo ---
"""
A port of the code from this stack overflow answer:
https://stackoverflow.com/a/4204758
```c
#include <dirent.h>
#include <stdio.h>
int main(void) {
DIR *d;
struct dirent *dir;
d = opendir(".");
if (d) {
while ((dir = readdir(d)) != NULL) {
printf("%s\n", dir->d_name);
}
closedir(d);
}
return(0);
}
```
"""
from memory.unsafe import Pointer
from sys.info import sizeof
@value
@register_passable("trivial")
struct DIR:
pass
@value
@register_passable("trivial")
struct dirent:
var d_ino: UInt64
var d_off: UInt64
var d_reclen: UInt16
var d_type: UInt8
var d_name: Pointer[UInt8]
@always_inline
fn closedir(arg: Pointer[DIR]) -> Int32:
return external_call["closedir", Int32, Pointer[DIR]](arg)
@always_inline
fn opendir(arg: Pointer[UInt8]) -> Pointer[DIR]:
return external_call["opendir", Pointer[DIR], Pointer[UInt8]](arg)
@always_inline
fn readdir(arg: Pointer[DIR]) -> Pointer[dirent]:
return external_call["readdir", Pointer[dirent], Pointer[DIR]](arg)
@always_inline
fn fdopendir(arg: Int32) -> DIR:
return external_call["fdopendir", DIR](arg)
# based on "https://github.com/crisadamo/mojo-libc/blob/main/Libc.mojo"
@always_inline
fn str_to_cstring(s: String) -> Pointer[UInt8]:
let ptr = Pointer[UInt8].alloc(len(s) + 1)
for i in range(len(s)):
ptr.store(i, ord(s[i]))
ptr.store(len(s), ord("\0"))
return ptr
fn main():
var dir = Pointer[dirent]()
let path = str_to_cstring(".")
let d = opendir(path)
if d:
while dir := readdir(d):
let direntry = dir.load(0)
# let dname = StringRef(
# direntry.d_name.bitcast[__mlir_type.`!pop.scalar<si8>`]().address,
# direntry.d_reclen.to_int(),
# )
let ptr = dir.bitcast[__mlir_type.`!pop.scalar<si8>`]().offset(
sizeof[UInt64]() * 2 + sizeof[UInt16]() + sizeof[UInt8]()
).address
let dname = StringRef(
ptr,
dir.load(0).d_reclen.to_int(),
)
print(dname)
let _closed_ok = closedir(d)
path.free()
--- file/__init__.mojo ---
from memory import memset
from math import min
from shims.libc.stdio import fopen, fread, fclose, fwrite
from shims.libc.string import strnlen
alias c_char = UInt8
alias FILE = UInt64
alias BUF_SIZE = 4096
fn to_char_ptr(s: String) -> Pointer[c_char]:
"""Only ASCII-based strings."""
let ptr = Pointer[c_char]().alloc(len(s) + 1)
for i in range(len(s)):
ptr.store(i, ord(s[i]))
ptr.store(len(s), ord("\0"))
return ptr
struct File:
var handle: Pointer[UInt64]
var fname: Pointer[c_char]
var mode: Pointer[c_char]
fn __init__(inout self, filename: String, mode: StringLiteral):
let fname = to_char_ptr(filename)
let mode_cstr = to_char_ptr(mode)
let handle = fopen(fname, mode_cstr)
self.fname = fname
self.mode = mode_cstr
self.handle = handle
fn __bool__(self) -> Bool:
return self.handle.__bool__()
fn __del__(owned self) raises:
if self.handle:
pass
# TODO: uncomment when external_call resolution bug is fixed
# let c = fclose(self.handle)
# if c != 0:
# raise Error("Failed to close file")
if self.fname:
self.fname.free()
if self.mode:
self.mode.free()
fn __moveinit__(inout self, owned other: Self):
self.fname = other.fname
self.mode = other.mode
self.handle = other.handle
other.handle = Pointer[FILE]()
other.fname = Pointer[c_char]()
other.mode = Pointer[c_char]()
fn do_nothing(self):
pass
fn read[D: Dim](self, buffer: Buffer[D, DType.uint8]) raises -> Int:
return fread(
buffer.data.as_scalar_pointer(), sizeof[UInt8](), BUF_SIZE, self.handle
).to_int()
fn write[D: Dim](self, buffer: Buffer[D, DType.uint8]) raises -> Int:
return fwrite(
buffer.data.as_scalar_pointer(), sizeof[UInt8](), len(buffer), self.handle
).to_int()
fn write_all[D: Dim](self, buffer: Buffer[D, DType.uint8]) raises:
var index = 0
while index != len(buffer):
index += self.write(buffer)
fn write_byte(self, byte: UInt8) raises:
let buf = Buffer[1, DType.uint8]().stack_allocation()
buf[0] = byte
self.write_all(buf)
fn write_byte_n_times(self, byte: UInt8, n: Int) raises:
var bytes = StaticTuple[256, UInt8]()
let bytes_ptr = DTypePointer[DType.uint8](
Pointer.address_of(bytes).bitcast[UInt8]()
)
memset[DType.uint8](
bytes_ptr,
byte,
256,
)
var remaining = n
while remaining > 0:
let to_write = min(remaining, bytes.__len__())
self.write_all(Buffer[Dim(), DType.uint8](bytes_ptr, to_write))
remaining -= to_write
--- libc/__init__.mojo ---
--- libc/dirent/__init__.mojo ---
from memory.unsafe import Pointer
@value
@register_passable("trivial")
struct DIR:
pass
@value
@register_passable("trivial")
struct dirent:
var d_ino: UInt64
var d_off: UInt64
var d_reclen: UInt16
var d_type: UInt8
var d_name: Pointer[UInt8]
fn closedir(arg: Pointer[DIR]) -> Int32:
return external_call["closedir", Int32, Pointer[DIR]](arg)
fn opendir(arg: Pointer[UInt8]) -> Pointer[DIR]:
return external_call["opendir", Pointer[DIR], Pointer[UInt8]](arg)
fn readdir(arg: Pointer[DIR]) -> Pointer[dirent]:
return external_call["readdir", Pointer[dirent], Pointer[DIR]](arg)
fn fdopendir(arg: Int32) -> DIR:
return external_call["fdopendir", DIR](arg)
--- libc/stdio/__init__.mojo ---
from memory.unsafe import Pointer
alias FILE = UInt64
fn clearerr(arg: Pointer[FILE]) -> UInt8:
return external_call["clearerr", UInt8, Pointer[FILE]](arg)
fn fclose(arg: Pointer[FILE]) -> Int32:
return external_call["fclose", Int32, Pointer[FILE]](arg)
fn feof(arg: Pointer[FILE]) -> Int32:
return external_call["feof", Int32, Pointer[FILE]](arg)
fn ferror(arg: Pointer[FILE]) -> Int32:
return external_call["ferror", Int32, Pointer[FILE]](arg)
fn fflush(arg: Pointer[FILE]) -> Int32:
return external_call["fflush", Int32, Pointer[FILE]](arg)
fn fgetc(arg: Pointer[FILE]) -> Int32:
return external_call["fgetc", Int32, Pointer[FILE]](arg)
fn fopen(__filename: Pointer[UInt8], __mode: Pointer[UInt8]) -> Pointer[FILE]:
return external_call["fopen", Pointer[FILE], Pointer[UInt8], Pointer[UInt8]](
__filename, __mode
)
fn fwrite(
__ptr: Pointer[UInt8], __size: UInt64, __nitems: UInt64, __stream: Pointer[FILE]
) -> UInt64:
return external_call[
"fwrite", UInt64, Pointer[UInt8], UInt64, UInt64, Pointer[FILE]
](__ptr, __size, __nitems, __stream)
fn fread(
__ptr: Pointer[UInt8], __size: UInt64, __nitems: UInt64, __stream: Pointer[FILE]
) -> UInt64:
return external_call[
"fread", UInt64, Pointer[UInt8], UInt64, UInt64, Pointer[FILE]
](__ptr, __size, __nitems, __stream)
--- libc/string/__init__.mojo ---
from memory.unsafe import Pointer
fn strnlen(pointer: Pointer[UInt8]) -> Int:
return external_call["strnlen", Int, Pointer[UInt8]](pointer)
--- read/__init__.mojo ---
"""
This is a port of Zig's buffered reader.
See: https://github.com/ziglang/zig/blob/master/lib/std/io/buffered_reader.zig
Example usage:
==============
from shims.file import File
from shims.read import BufReader
from memory.buffer import Buffer
fn main() raises:
let f = File("file.txt")
var reader = BufReader[4096](f ^)
let buf = Buffer[256, DType.uint8]().stack_allocation()
var bytes_read = 1
while bytes_read > 0:
bytes_read = reader.read(buf)
print(
StringRef(
buf.data.as_scalar_pointer()
.bitcast[__mlir_type.`!pop.scalar<si8>`]()
.address,
bytes_read,
)
)
"""
from utils.list import Dim
from math import min, abs
from math.limit import max_finite
from memory import memcpy
from memory.buffer import Buffer
from memory.unsafe import Pointer, DTypePointer
from sys.info import sizeof
from utils.index import Index
from utils.vector import DynamicVector
import testing
from shims.file import File
# Types aliases
alias c_char = UInt8
struct BufReader[BUF_SIZE: Int]:
var unbuffered_reader: File
var data: DTypePointer[DType.uint8]
var end: Int
var start: Int
fn __init__(inout self, owned reader: File):
self.unbuffered_reader = reader ^
self.data = DTypePointer[DType.uint8]().alloc(BUF_SIZE)
self.end = 0
self.start = 0
fn __moveinit__(inout self, owned other: Self):
self.unbuffered_reader = other.unbuffered_reader ^
self.data = other.data
self.end = other.end
self.start = other.start
other.unbuffered_reader = File("", "r")
other.data = DTypePointer[DType.uint8]()
fn read[D: Dim](inout self, dest: Buffer[D, DType.uint8]) raises -> Int:
var dest_index = 0
let buf = Buffer[BUF_SIZE, DType.uint8](self.data)
while dest_index < len(dest):
let written = min(len(dest) - dest_index, self.end - self.start)
memcpy(dest.data.offset(dest_index), self.data.offset(self.start), written)
if written == 0:
# buf empty, fill it
let n = self.unbuffered_reader.read(buf)
if n == 0:
# reading from the unbuffered stream returned nothing
# so we have nothing left to read.
return dest_index
self.start = 0
self.end = n
self.start += written
dest_index += written
return len(dest)
fn do_nothing(self):
pass
struct Reader[BUF_SIZE: Int]:
var context: BufReader[BUF_SIZE]
fn do_nothing(self):
pass
fn __init__(inout self, owned context: BufReader[BUF_SIZE]):
self.context = context ^
# Returns the number of bytes read. It may be less than buffer.len.
# If the number of bytes read is 0, it means end of stream.
# End of stream is not an error condition.
fn read[D: Dim](inout self, buffer: Buffer[D, DType.uint8]) raises -> Int:
return self.context.read(buffer)
# Returns the number of bytes read. If the number read is smaller than `buffer.len`, it
# means the stream reached the end. Reaching the end of a stream is not an error
# condition.
fn read_all[D: Dim](inout self, buffer: Buffer[D, DType.uint8]) raises -> Int:
return self.read_at_least(buffer, len(buffer))
# Returns the number of bytes read, calling the underlying read
# function the minimal number of times until the buffer has at least
# `len` bytes filled. If the number read is less than `len` it means
# the stream reached the end. Reaching the end of the stream is not
# an error condition.
fn read_at_least[
D: Dim
](inout self, buffer: Buffer[D, DType.uint8], len: Int) raises -> Int:
# assert(len <= buffer.len);
var index: Int = 0
while index < len:
let amt = self.read(
Buffer[Dim(), DType.uint8](
buffer.data.offset(index), buffer.__len__() - index
)
)
if amt == 0:
break
index += amt
return index
# If the number read would be smaller than `buf.len`, `error.EndOfStream` is returned instead.
fn read_no_eof[D: Dim](inout self, buf: Buffer[D, DType.uint8]) raises:
let amt_read = self.read_all(buf)
if amt_read < len(buf):
raise Error("Unexpected End of Stream.")
# Appends to the `writer` contents by reading from the stream until `delimiter` is found.
# Does not write the delimiter itself.
# If `optional_max_size` is not null and amount of written bytes exceeds `optional_max_size`,
# returns `error.StreamTooLong` and finishes appending.
# If `optional_max_size` is null, appending is unbounded.
fn stream_until_delimiter[
BuffD: Dim
](
inout self,
inout writer: FixedBufferStream[BuffD],
delimiter: UInt8,
max_size: Int,
) raises:
for i in range(max_size):
let byte = self.read_byte()
if byte == delimiter:
return
writer.write_byte(byte)
raise Error("Stream too long")
# Appends to the `writer` contents by reading from the stream until `delimiter` is found.
# Does not write the delimiter itself.
# If `optional_max_size` is not null and amount of written bytes exceeds `optional_max_size`,
# returns `error.StreamTooLong` and finishes appending.
# If `optional_max_size` is null, appending is unbounded.
fn stream_until_delimiter[
BuffD: Dim
](inout self, inout writer: FixedBufferStream[BuffD], delimiter: UInt8) raises:
while True:
let byte = self.read_byte()
if byte == delimiter:
return
writer.write_byte(byte)
# Reads 1 byte from the stream or returns `error.EndOfStream`.
fn read_byte(inout self) raises -> UInt8:
let result = Buffer[1, DType.uint8]().stack_allocation()
let amt_read = self.read(result)
if amt_read < 1:
raise Error("End of stream")
return result[0]
@value
struct FixedBufferStream[D: Dim]:
var buffer: Buffer[D, DType.uint8]
var pos: Int
@always_inline
fn __init__(inout self, buffer: Buffer[D, DType.uint8]):
self.buffer = buffer
self.pos = 0
@always_inline
fn read[
DestDim: Dim
](inout self, destination: Buffer[DestDim, DType.uint8]) raises -> Int:
let size = min(len(destination), len(self.buffer) - self.pos)
let end = self.pos + size
memcpy(destination.data, self.buffer.data.offset(self.pos), size)
self.pos = end
return size
# If the returned number of bytes written is less than requested, the
# buffer is full. Returns `error.NoSpaceLeft` when no bytes would be written.
# Note: `error.NoSpaceLeft` matches the corresponding error from
# `std.fs.File.WriteError`.
fn write[BuffD: Dim](inout self, bytes: Buffer[BuffD, DType.uint8]) raises -> Int:
if len(bytes) == 0:
return 0
if self.pos >= len(self.buffer):
raise Error("No space left")
let n = len(bytes) if self.pos + len(bytes) <= len(self.buffer) else len(
self.buffer
) - self.pos
memcpy(self.buffer.data.offset(self.pos), bytes.data, n)
self.pos += n
if n == 0:
raise Error("No space left")
return n
fn write_all[BuffD: Dim](inout self, bytes: Buffer[BuffD, DType.uint8]) raises:
var index = 0
while index != len(bytes):
index += self.write(
Buffer[Dim(), DType.uint8](bytes.data.offset(index), len(bytes) - index)
)
fn write_byte(inout self, byte: UInt8) raises:
let arr = Buffer[1, DType.uint8]().stack_allocation()
self.write_all(arr)
fn seek_to(inout self, pos: Int) raises:
self.pos = min(len(self.buffer), pos)
fn seek_by(inout self, amt: Int) raises:
if amt < 0:
let abs_amt = abs(amt)
if abs_amt > self.pos:
self.pos = 0
else:
self.pos -= abs_amt
else:
let new_pos = self.pos + amt
self.pos = min(len(self.buffer), new_pos)
@always_inline
fn get_end_pos(self) -> Int:
return len(self.buffer)
@always_inline
fn get_pos(self) -> Int:
return self.pos
@always_inline
fn get_written(self) -> Buffer[Dim(), DType.uint8]:
return Buffer[Dim(), DType.uint8](self.buffer.data, self.pos)
@always_inline
fn reset(inout self):
self.pos = 0
--- siphash/__init__.mojo ---
"""
This is a port of Zig's SipHash
See: https://github.com/ziglang/zig/blob/master/lib/std/crypto/siphash.zig
"""
from memory.buffer import Buffer
from utils.list import Dim
from memory import memcpy, memset_zero
from memory.unsafe import Pointer, DTypePointer
from sys.info import sizeof
from math import rotate_bits_left
from utils.static_tuple import StaticTuple
from math import min
from algorithm.functional import parallelize
import testing
from shims.bitcast import from_be_bytes, from_le_bytes, to_le_bytes
@always_inline
fn slice_buf[T: DType, D: Dim](b: Buffer[D, T], slc: slice) -> Buffer[Dim(), T]:
return Buffer[Dim(), T](b.data.offset(slc.start), slc.__len__())
@value
struct SipHashStateless[T: DType, C_ROUNDS: Int, D_ROUNDS: Int]:
alias block_length = 64
alias key_length = 16
var v0: UInt64
var v1: UInt64
var v2: UInt64
var v3: UInt64
var msg_len: UInt8
@always_inline
fn __init__(inout self, key: Buffer[Self.key_length, DType.uint8]) raises:
# constrained[T == DType.uint64 or T == DType.uint128]()
constrained[T == DType.uint64]()
constrained[C_ROUNDS > 0 and D_ROUNDS > 0]()
let k0: UInt64 = from_le_bytes[DType.uint64](key.simd_load[sizeof[UInt64]()](0))
let k1: UInt64 = from_le_bytes[DType.uint64](key.simd_load[sizeof[UInt64]()](8))
self.v0 = k0 ^ UInt64(0x736F6D6570736575)
self.v1 = k1 ^ UInt64(0x646F72616E646F6D)
self.v2 = k0 ^ UInt64(0x6C7967656E657261)
self.v3 = k1 ^ UInt64(0x7465646279746573)
self.msg_len = UInt8(0)
# @parameter if T == DType.128:
# self.v1 ^= 0xee;
@always_inline
fn update[D: Dim](inout self, b: Buffer[D, DType.uint8]):
# std.debug.assert(b.len % 8 == 0);
for off in range(0, len(b), 8):
let blob = b.simd_load[8](off)
self.round(blob)
self.msg_len += UInt8(len(b))
fn final[D: Dim](inout self, b: Buffer[D, DType.uint8]) -> SIMD[T, 1]:
# constrained[len(b) < 8](b.len < 8);
self.msg_len += UInt8(len(b))
let buf = Buffer[8, DType.uint8]().stack_allocation()
memset_zero(buf.data, 8)
memcpy(buf.data, b.data, len(b))
buf[7] = self.msg_len
self.round(buf.simd_load[8](0))
@parameter
if T == DType.uint64:
self.v2 ^= 0xFF
else:
self.v2 ^= 0xEE
@unroll
for _ in range(D_ROUNDS):
self.sip_round()
let b1 = (self.v0 ^ self.v1 ^ self.v2 ^ self.v3).to_int()
return SIMD[T, 1](b1)
## TODO: remove above return when UInt128 is available
# @parameter if T == dtype.uint64:
# return b1
# self.v1 ^= 0xdd;
# @unroll
# for _ in range(D_ROUNDS):
# self.sip_round()
# let b2 = self.v0 ^ self.v1 ^ self.v2 ^ self.v3;
# return (UInt128(b2) << 64) | b1
@always_inline
fn round(inout self, owned b: SIMD[DType.uint8, 8]):
var m_buf = SIMD[DType.uint8, sizeof[UInt64]()]()
@unroll
for i in range(8):
m_buf[i] = b[i]
let m = from_le_bytes[DType.uint64](m_buf)
self.v3 ^= m
@unroll
for i in range(C_ROUNDS):
self.sip_round()
self.v0 ^= m
@always_inline
fn sip_round(inout self):
self.v0 += self.v1
self.v1 = rotate_bits_left[13](self.v1)
self.v1 ^= self.v0
self.v0 = rotate_bits_left[32](self.v0)
self.v2 += self.v3
self.v3 = rotate_bits_left[16](self.v3)
self.v3 ^= self.v2
self.v0 += self.v3
self.v3 = rotate_bits_left[21](self.v3)
self.v3 ^= self.v0
self.v2 += self.v1
self.v1 = rotate_bits_left[17](self.v1)
self.v1 ^= self.v2
self.v2 = rotate_bits_left[32](self.v2)
@staticmethod
fn hash[
MsgD: Dim
](
msg: Buffer[MsgD, DType.uint8], key: Buffer[Self.key_length, DType.uint8]
) raises -> SIMD[T, 1]:
let aligned_len = len(msg) - (len(msg) % 8)
var c = Self(key)
c.update(slice_buf(msg, slice(0, aligned_len)))
return c.final(slice_buf(msg, slice(aligned_len, len(msg))))
@value
struct SipHash[T: DType, C_ROUNDS: Int, D_ROUNDS: Int]:
alias key_length = 16
alias mac_length = sizeof[SIMD[T, 1]]()
alias block_length = 8
alias State = SipHashStateless[T, C_ROUNDS, D_ROUNDS]
var state: Self.State
var ptr: DTypePointer[DType.uint8]
var buf: Buffer[8, DType.uint8]
var buf_len: Int
fn __init__(inout self, key: Buffer[Self.key_length, DType.uint8]) raises:
# constrained[T == DType.uint64 or T== DType.uint128]()
constrained[T == DType.uint64]()
constrained[C_ROUNDS > 0 and D_ROUNDS > 0]()
self.state = SipHashStateless[T, C_ROUNDS, D_ROUNDS](key)
self.ptr = DTypePointer[DType.uint8]().alloc(8)
self.buf = Buffer[8, DType.uint8](self.ptr)
self.buf_len = 0
fn update(inout self, b: Buffer[Dim(), DType.uint8]):
"""
Add data to the state.
"""
var off = 0
if self.buf_len != 0 and self.buf_len + len(b) >= 8:
off += 8 - self.buf_len
memcpy(self.buf.data.offset(self.buf_len), b.data, off)
self.state.update(self.buf)
self.buf_len = 0
let remain_len = len(b) - off
let aligned_len = remain_len - (remain_len % 8)
self.state.update(slice_buf(b, slice(off, off + aligned_len)))
let b_slice = slice_buf(b, slice(off + aligned_len, len(b)))
memcpy(self.buf.data.offset(self.buf_len), b_slice.data, len(b_slice))
self.buf_len += len(b_slice)
fn peek(self) -> Buffer[Self.mac_length, DType.uint8]:
var copy = self
return copy.final_result()
fn final(inout self, out: Buffer[Self.mac_length, DType.uint8]):
"""
Return an authentication tag for the current state
Assumes `out` is less than or equal to `mac_length`.
"""
let s = self.state.final(slice_buf(self.buf, slice(0, self.buf_len)))
let bytes = to_le_bytes(s)
out.simd_store[Self.mac_length](0, bytes)
fn final_result(inout self) -> Buffer[Self.mac_length, DType.uint8]:
let result = Buffer[Self.mac_length, DType.uint8]().stack_allocation()
self.final(result)
return result
@staticmethod
fn create(
out: Buffer[Self.mac_length, DType.uint8],
msg: Buffer[Dim(), DType.uint8],
key: Buffer[Self.key_length, DType.uint8],
) raises:
"""
Return an authentication tag for a message and a key.
"""
var ctx = Self(key)
ctx.update(msg)
ctx.final(out)
fn final_int(inout self) -> SIMD[T, 1]:
"""
Return an authentication tag for the current state, as an integer.
"""
return self.state.final(slice_buf(self.buf, slice(0, self.buf_len)))
@staticmethod
fn to_int(
msg: Buffer[Dim(), DType.uint8],
key: Buffer[Self.key_length, DType.uint8],
) raises -> SIMD[T, 1]:
"""
Return an authentication tag for a message and a key, as an integer.
"""
return Self.State.hash(msg, key)
fn __del__(owned self):
self.ptr.free()
alias UInt8x8 = SIMD[DType.uint8, 8]
alias SipHash24 = SipHash[DType.uint64, 2, 4]
alias TEST_DATA_LEN = 63
alias TEST_DATA: StaticTuple[TEST_DATA_LEN, SIMD[DType.uint8, 8]] = StaticTuple[
63, SIMD[DType.uint8, 8]
](
SIMD[DType.uint8, 8](49, 14, 14, 221, 71, 219, 111, 114),
SIMD[DType.uint8, 8](253, 103, 220, 147, 197, 57, 248, 116),
SIMD[DType.uint8, 8](90, 79, 169, 217, 9, 128, 108, 13),
SIMD[DType.uint8, 8](45, 126, 251, 215, 150, 102, 103, 133),
SIMD[DType.uint8, 8](183, 135, 113, 39, 224, 148, 39, 207),
SIMD[DType.uint8, 8](141, 166, 153, 205, 100, 85, 118, 24),
SIMD[DType.uint8, 8](206, 227, 254, 88, 110, 70, 201, 203),
SIMD[DType.uint8, 8](55, 209, 1, 139, 245, 0, 2, 171),
SIMD[DType.uint8, 8](98, 36, 147, 154, 121, 245, 245, 147),
SIMD[DType.uint8, 8](176, 228, 169, 11, 223, 130, 0, 158),
SIMD[DType.uint8, 8](243, 185, 221, 148, 197, 187, 93, 122),
SIMD[DType.uint8, 8](167, 173, 107, 34, 70, 47, 179, 244),
SIMD[DType.uint8, 8](251, 229, 14, 134, 188, 143, 30, 117),
SIMD[DType.uint8, 8](144, 61, 132, 192, 39, 86, 234, 20),
SIMD[DType.uint8, 8](238, 242, 122, 142, 144, 202, 35, 247),
SIMD[DType.uint8, 8](229, 69, 190, 73, 97, 202, 41, 161),
SIMD[DType.uint8, 8](219, 155, 194, 87, 127, 204, 42, 63),
SIMD[DType.uint8, 8](148, 71, 190, 44, 245, 233, 154, 105),
SIMD[DType.uint8, 8](156, 211, 141, 150, 240, 179, 193, 75),
SIMD[DType.uint8, 8](189, 97, 121, 167, 29, 201, 109, 187),
SIMD[DType.uint8, 8](152, 238, 162, 26, 242, 92, 214, 190),
SIMD[DType.uint8, 8](199, 103, 59, 46, 176, 203, 242, 208),
SIMD[DType.uint8, 8](136, 62, 163, 227, 149, 103, 83, 147),
SIMD[DType.uint8, 8](200, 206, 92, 205, 140, 3, 12, 168),
SIMD[DType.uint8, 8](148, 175, 73, 246, 198, 80, 173, 184),
SIMD[DType.uint8, 8](234, 184, 133, 138, 222, 146, 225, 188),
SIMD[DType.uint8, 8](243, 21, 187, 91, 184, 53, 216, 23),
SIMD[DType.uint8, 8](173, 207, 107, 7, 99, 97, 46, 47),
SIMD[DType.uint8, 8](165, 201, 29, 167, 172, 170, 77, 222),
SIMD[DType.uint8, 8](113, 101, 149, 135, 102, 80, 162, 166),
SIMD[DType.uint8, 8](40, 239, 73, 92, 83, 163, 135, 173),
SIMD[DType.uint8, 8](66, 195, 65, 216, 250, 146, 216, 50),
SIMD[DType.uint8, 8](206, 124, 242, 114, 47, 81, 39, 113),
SIMD[DType.uint8, 8](227, 120, 89, 249, 70, 35, 243, 167),
SIMD[DType.uint8, 8](56, 18, 5, 187, 26, 176, 224, 18),
SIMD[DType.uint8, 8](174, 151, 161, 15, 212, 52, 224, 21),
SIMD[DType.uint8, 8](180, 163, 21, 8, 190, 255, 77, 49),
SIMD[DType.uint8, 8](129, 57, 98, 41, 240, 144, 121, 2),
SIMD[DType.uint8, 8](77, 12, 244, 158, 229, 212, 220, 202),
SIMD[DType.uint8, 8](92, 115, 51, 106, 118, 216, 191, 154),
SIMD[DType.uint8, 8](208, 167, 4, 83, 107, 169, 62, 14),
SIMD[DType.uint8, 8](146, 89, 88, 252, 214, 66, 12, 173),
SIMD[DType.uint8, 8](169, 21, 194, 155, 200, 6, 115, 24),
SIMD[DType.uint8, 8](149, 43, 121, 243, 188, 10, 166, 212),
SIMD[DType.uint8, 8](242, 29, 242, 228, 29, 69, 53, 249),
SIMD[DType.uint8, 8](135, 87, 117, 25, 4, 143, 83, 169),
SIMD[DType.uint8, 8](16, 165, 108, 245, 223, 205, 154, 219),
SIMD[DType.uint8, 8](235, 117, 9, 92, 205, 152, 108, 208),
SIMD[DType.uint8, 8](81, 169, 203, 158, 203, 163, 18, 230),
SIMD[DType.uint8, 8](150, 175, 173, 252, 44, 230, 102, 199),
SIMD[DType.uint8, 8](114, 254, 82, 151, 90, 67, 100, 238),
SIMD[DType.uint8, 8](90, 22, 69, 178, 118, 213, 146, 161),
SIMD[DType.uint8, 8](178, 116, 203, 142, 191, 135, 135, 10),
SIMD[DType.uint8, 8](111, 155, 180, 32, 61, 231, 179, 129),
SIMD[DType.uint8, 8](234, 236, 178, 163, 11, 34, 168, 127),
SIMD[DType.uint8, 8](153, 36, 164, 60, 193, 49, 87, 36),
SIMD[DType.uint8, 8](189, 131, 141, 58, 175, 191, 141, 183),
SIMD[DType.uint8, 8](11, 26, 42, 50, 101, 213, 26, 234),
SIMD[DType.uint8, 8](19, 80, 121, 163, 35, 28, 230, 96),
SIMD[DType.uint8, 8](147, 43, 40, 70, 228, 215, 6, 102),
SIMD[DType.uint8, 8](225, 145, 95, 92, 177, 236, 164, 108),
SIMD[DType.uint8, 8](243, 37, 150, 92, 161, 109, 98, 159),
SIMD[DType.uint8, 8](87, 95, 242, 142, 96, 56, 27, 229),
SIMD[DType.uint8, 8](114, 69, 6, 235, 76, 50, 138, 149),
)
fn test_siphash64_2_4(test_key: Buffer[16, DType.uint8]) raises:
let msg = Buffer[64, DType.uint8]().stack_allocation()
for i in range(TEST_DATA_LEN):
msg[i] = i
@parameter
fn test_inner(i: Int):
let out = Buffer[SipHash24.mac_length, DType.uint8]().stack_allocation()
try:
SipHash24.create(out, slice_buf(msg, slice(0, i)), test_key)
except:
print("failed on test: ", i)
let out_str = String(
StringRef(out.data.bitcast[DType.int8]().address, SipHash24.mac_length)
)
var vector = TEST_DATA[i]
let vector_str = String(
StringRef(
Pointer.address_of[SIMD[DType.uint8, 8]](vector)
.bitcast[__mlir_type.`!pop.scalar<si8>`]()
.address,
SipHash24.mac_length,
)
)
if not testing.assert_equal(vector_str, out_str):
pass
parallelize[test_inner](TEST_DATA_LEN)
fn test_iterative_non_divisible_update() raises:
alias BUF_LEN = 1024
let buf = Buffer[BUF_LEN, DType.uint8]().stack_allocation()
@unroll
for i in range(BUF_LEN):
buf[i] = i
let key_str = String("0x128dad08f12307")
let key = Buffer[SipHash24.key_length, DType.uint8]().stack_allocation()
for i in range(SipHash24.key_length):
key[i] = ord(key_str[i])
let end = 9
for _ in range(end, len(buf), 9):
let non_iterative_hash = SipHash24.to_int(slice_buf(buf, slice(0, end)), key)
var siphash = SipHash24(key)
for i in range(0, end, 7):
siphash.update(slice_buf(buf, slice(i, min(i + 7, end))))
let iterative_hash = siphash.final_int()
if not testing.assert_equal(iterative_hash, non_iterative_hash):
raise Error("failed")
fn run_tests() raises:
# Test vectors from reference implementation.
# https://github.com/veorq/SipHash/blob/master/vectors.h
let bufptr = DTypePointer[DType.uint8]().alloc(16)
let test_key = Buffer[
16,
DType.uint8,
](bufptr)
test_key.simd_store[16](
0,
SIMD[DType.uint8, 16](
0x00,
0x01,
0x02,
0x03,
0x04,
0x05,
0x06,
0x07,
0x08,
0x09,
0xA,
0xB,
0xC,
0x0D,
0x0E,
0x0F,
),
)
test_siphash64_2_4(test_key)
test_iterative_non_divisible_update()
--- write/__init__.mojo ---
"""
A port of Zig's BufferedReader.
Example:
========
from shims.file import File
from shims.read import BufReader
from shims.write import BufWriter
from memory.buffer import Buffer
fn main() raises:
let f = File("a.txt", "r")
let out_f = File("a2.txt", "w+")
var reader = BufReader[4096](f ^)
var writer = BufWriter[4096](out_f ^)
let buf = Buffer[256, DType.uint8]().stack_allocation()
var bytes_read = 1
while bytes_read > 0:
bytes_read = reader.read(buf)
if bytes_read > 0:
print(
StringRef(
buf.data.as_scalar_pointer()
.bitcast[__mlir_type.`!pop.scalar<si8>`]()
.address,
bytes_read,
)
)
let write_buf = Buffer[Dim(), DType.uint8](buf.data, bytes_read)
let bytes_written = writer.write(write_buf)
_ = bytes_written
"""
from shims.file import File
from memory import memcpy
struct BufWriter[BUF_SIZE: Int]:
var unbuffered_writer: File
var data: DTypePointer[DType.uint8]
var end: Int
fn __init__(inout self, owned writer: File):
self.unbuffered_writer = writer ^
self.data = DTypePointer[DType.uint8]().alloc(BUF_SIZE)
self.end = 0
fn __del__(owned self) raises:
self.flush()
fn flush(inout self) raises:
self.unbuffered_writer.write_all(
Buffer[Dim(), DType.uint8](self.data, self.end)
)
self.end = 0
fn write[D: Dim](inout self, bytes: Buffer[D, DType.uint8]) raises -> Int:
if self.end + len(bytes) > BUF_SIZE:
self.flush()
if len(bytes) > BUF_SIZE:
return self.unbuffered_writer.write(bytes)
let new_end = self.end + len(bytes)
memcpy(self.data.offset(self.end), bytes.data, new_end - self.end)
self.end = new_end
return len(bytes)
fn write(inout self, str: StringRef) raises -> Int:
var strbuf = DynamicVector[UInt8]()
for i in range(len(str)):
strbuf.push_back(ord(str[i]))
let buf = Buffer[Dim(), DType.uint8](strbuf.data, len(strbuf))
return self.write(buf)
--- wyhash/__init__.mojo ---
"""
A port of Zig's Wyhash
See: https://github.com/ziglang/zig/blob/master/lib/std/hash/wyhash.zig
"""
from memory.unsafe import DTypePointer, Pointer
from memory import memcpy, memset_zero, stack_allocation
from utils.static_tuple import StaticTuple
from utils.list import Dim
import testing
from shims.bitcast import from_le_bytes
alias UInt64x4 = SIMD[DType.uint64, 4]
@always_inline
fn mum(inout a: UInt64, inout b: UInt64):
let x = _umul128(a, b)
a = x[0]
b = x[1]
@always_inline
fn mix(a_: UInt64, b_: UInt64) -> UInt64:
var a = a_
var b = b_
mum(a, b)
return a ^ b
@always_inline
fn _umul128(multiplier: UInt64, multiplicand: UInt64) -> SIMD[DType.uint64, 2]:
"""Taken from stack overflow.
https://stackoverflow.com/a/46923106
"""
# multiplier = ab = a * 2^32 + b
# multiplicand = cd = c * 2^32 + d
# ab * cd = a * c * 2^64 + (a * d + b * c) * 2^32 + b * d
let a = multiplier >> 32
let b = multiplier & 0xFFFFFFFF
let c = multiplicand >> 32
let d = multiplicand & 0xFFFFFFFF
# let ac = a * c
let ad = a * d
# let bc = b * c
let bd = b * d
let adbc = ad + (b * c)
let adbc_carry = 1 if adbc < ad else 0
# multiplier * multiplicand = product_hi * 2^64 + product_lo
let product_lo = bd + (adbc << 32)
let product_lo_carry = 1 if product_lo < bd else 0
let product_hi = (a * c) + (adbc >> 32) + (adbc_carry << 32) + product_lo_carry
return SIMD[DType.uint64, 2](product_hi, product_lo)
fn test_umul128() raises:
let a: UInt64
let b: UInt64
a, b = UInt64(0x0FFFFFFFFFFFFFFF), UInt64(0xF0000000)
# testing.assert_equal(
# _umul128(a, b), SIMD[DType.uint64, 2](0xEFFFFFF, 0xFFFFFFFF10000000)
# )
struct Wyhash:
var _secret: UInt64x4
var a: UInt64
var b: UInt64
# we only care about the first three values
var state: StaticTuple[3, UInt64]
var total_len: Int
var buf: StaticTuple[48, UInt8]
var buf_len: Int
fn __init__(inout self, seed: UInt64):
self._secret = SIMD[DType.uint64, 4](
0xA0761D6478BD642F,
0xE7037ED1A0B428DB,
0x8EBC6AF09C88C6E3,
0x589965CC75374CC3,
)
self.a = 0
self.b = 0
self.buf_len = 0
self.total_len = 0
self.state = StaticTuple[3, UInt64]()
self.buf = StaticTuple[48, UInt8]()
memset_zero(Pointer.address_of(self.buf).bitcast[UInt8](), 48)
self.state[0] = seed ^ mix(seed ^ self._secret[0], self._secret[1])
self.state[1] = self.state[0]
self.state[2] = self.state[0]
@always_inline
fn __copyinit__(inout self, other: Self):
self.a = other.a
self.b = other.b
self.state = other.state
self.total_len = other.total_len
self.buf_len = 0
self.buf = StaticTuple[48, UInt8]()
self._secret = UInt64x4(
0xA0761D6478BD642F,
0xE7037ED1A0B428DB,
0x8EBC6AF09C88C6E3,
0x589965CC75374CC3,
)
# This is subtly different from other hash function update calls. Wyhash requires the last
# full 48-byte block to be run through final1 if is exactly aligned to 48-bytes.
@always_inline
fn update[D: Dim](inout self, input: Buffer[D, DType.uint8]):
self.total_len += len(input)
if len(input) <= 48 - self.buf_len:
memcpy(
DTypePointer[DType.uint8](
Pointer.address_of(self.buf).bitcast[UInt8]().offset(self.buf_len)
),
input.data,
len(input),
)
self.buf_len += len(input)
return
var i = 0
if self.buf_len > 0:
i = 48 - self.buf_len
memcpy(
Pointer.address_of(self.buf).bitcast[UInt8]().offset(self.buf_len),
input.data,
i,
)
self.round(
Buffer[48, DType.uint8](Pointer.address_of(self.buf).bitcast[UInt8]())
)
self.buf_len = 0
for i in range(i, len(input), 48):
self.round(
Buffer[48, DType.uint8](input.data.offset(i).as_scalar_pointer())
)
let remaining_bytes = Buffer[Dim(), DType.uint8](
input.data.offset(i), len(input) - i
)
if len(remaining_bytes) < 16 and i >= 48:
let rem = 16 - len(remaining_bytes)
memcpy(
Pointer.address_of(self.buf)
.bitcast[UInt8]()
.offset(self.buf.__len__() - rem),
input.data.offset(i - rem),
i,
)
memcpy(
Pointer.address_of(self.buf).bitcast[UInt8](),
remaining_bytes.data.as_scalar_pointer(),
len(remaining_bytes),
)
self.buf_len = len(remaining_bytes)
@always_inline
fn final(inout self) -> UInt64:
let input_ptr = Pointer.address_of(self.buf).bitcast[UInt8]()
var input = Buffer[Dim(), DType.uint8](input_ptr, self.buf_len)
var new_self = self # ensure idempotency
if self.total_len <= 16:
new_self.small_key(input)
else:
var offset: Int = 0
if self.buf_len < 16:
var scratch = StaticTuple[16, UInt8]()
let scratch_pointer = Pointer.address_of(scratch).bitcast[UInt8]()
let buf_ptr = Pointer.address_of(self.buf).bitcast[UInt8]()
let rem = 16 - self.buf_len
memcpy(scratch_pointer, buf_ptr.offset(self.buf.__len__() - rem), rem)
memcpy(scratch_pointer.offset(rem), buf_ptr, self.buf_len)
# Same as input but with additional bytes preceeding start in case of a short buffer
input = Buffer[Dim(), DType.uint8](scratch_pointer, 16)
offset = rem
new_self.final0()
new_self.final1(input, offset)
return new_self.final2()
@staticmethod
fn hash[D: Dim](seed: UInt64, input: Buffer[D, DType.uint8]) -> UInt64:
var self = Self(seed)
if len(input) <= 16:
self.small_key(input)
else:
var i: Int = 0
if len(input) >= 48:
while i + 48 < len(input):
self.round(Buffer[48, DType.uint8](input.data.offset(i)))
i += 48
self.final0()
self.final1(input, i)
self.total_len = len(input)
return self.final2()
@always_inline
fn small_key[D: Dim](inout self, input: Buffer[D, DType.uint8]):
# constrained[D.get() <= 16]()
if len(input) >= 4:
let end = len(input) - 4
let quarter = (len(input) >> 3) << 2
# self.a = (
# UInt64(
# (
# from_le_bytes[DType.uint32](
# Buffer[sizeof[UInt32](), DType.uint8](input.data)
# )
# ).to_int()
# )
# << 32
# ) | UInt64(
# from_le_bytes[DType.uint32](
# Buffer[sizeof[UInt32](), DType.uint8](input.data.offset(quarter))
# ).to_int()
# )
# self.b = (
# UInt64(
# (
# from_le_bytes[DType.uint32](
# Buffer[sizeof[UInt32](), DType.uint8](
# input.data.offset(end)
# )
# )
# ).to_int()
# )
# << 32
# ) | UInt64(
# from_le_bytes[DType.uint32](
# Buffer[sizeof[UInt32](), DType.uint8](
# input.data.offset(end - quarter)
# )
# ).to_int()
# )
# elif len(input) > 0:
# self.a = (
# (UInt64(input[0].to_int()) << 16)
# | (UInt64(input[len(input) >> 1].to_int()) << 8)
# | UInt64(input[len(input) - 1].to_int())
# )
# self.b = 0
# else:
# self.a = 0
# self.b = 0
fn round(inout self, input: Buffer[48, DType.uint8]):
@unroll
for i in range(3):
# let a = from_le_bytes[DType.uint64](
# Buffer[sizeof[UInt64](), DType.uint8](input.data.offset(8 * (2 * i)))
# )
# let b = from_le_bytes[DType.uint64](
# Buffer[sizeof[UInt64](), DType.uint8](
# input.data.offset(8 * (2 * i + 1))
# )
# )
# self.state[i] = mix(a ^ self._secret[i + 1], b ^ self.state[i])
pass
@always_inline
fn final0(inout self):
self.state[0] ^= self.state[1] ^ self.state[2]
# input_lb must be at least 16-bytes long (in shorter key cases the smallKey function will be
# used instead). We use an index into a slice to for comptime processing as opposed to if we
# used pointers.
fn final1[D: Dim](inout self, input_lb: Buffer[D, DType.uint8], start_pos: Int):
# constrained(input_lb.len >= 16);
# constrained(input_lb.len - start_pos <= 48);
let input = Buffer[Dim(), DType.uint8](
input_lb.data.offset(start_pos), len(input_lb) - start_pos
)
for i in range(0, len(input), 16):
pass
# self.state[0] = mix(
# from_le_bytes[DType.uint64](
# Buffer[sizeof[UInt64](), DType.uint8](
# input.data.offset(i), len(input) - i
# )
# )
# ^ self._secret[1],
# from_le_bytes[DType.uint64](
# Buffer[sizeof[UInt64](), DType.uint8](
# input.data.offset(i + 8), len(input) - i + 8
# )
# )
# ^ self.state[0],
# )
# self.a = from_le_bytes[DType.uint64](
# Buffer[sizeof[UInt64](), DType.uint8](
# input_lb.data.offset(len(input_lb) - 16)
# )
# )
# self.b = from_le_bytes[DType.uint64](
# Buffer[sizeof[UInt64](), DType.uint8](
# input_lb.data.offset(len(input_lb) - 8)
# )
# )
@always_inline
fn final2(inout self) -> UInt64:
self.a ^= self._secret[1]
print(self._secret[1])
self.b ^= self.state[0]
mum(self.a, self.b)
return mix(self.a ^ self._secret[0] ^ self.total_len, self.b ^ self._secret[1])
--- README.md ---
# Mojo with Qt6
Install mojo and python.
```sh-session
$ curl -s https://get.modular.com | sh -
$ /opt/homebrew/bin/python3.11 -m venv venv
$ source venv/bin/activate
$ pip install PySide6
$ mojo qt.mojo
```
The demo launches a QML UI from mojo, and calls a mojo fn from QML when the button is clicked.
--- app.qml ---
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
Window {
width: 300
height: 200
visible: true
title: "Hello Mojo"
ColumnLayout {
anchors.fill: parent
Text {
id: text
text: "Hello World"
Layout.alignment: Qt.AlignHCenter
}
Button {
text: "Click me"
Layout.alignment: Qt.AlignHCenter
onClicked: on_clicked.invoke()
}
}
}
--- experiments/callback.mojo ---
from python import Python
fn callback() -> Int:
print("mojo callback running")
return 42
fn main() raises:
Python.add_to_path("./")
var callback_mod = Python.import_module("callback")
print("calling python callback from mojo")
var fn_address = UnsafePointer[fn () -> Int].address_of(callback).bitcast[Int64]()[0]
callback_mod.callback(fn_address)
--- experiments/callback.py ---
import ctypes
def callback(mojo_fn_address):
print(f"in python callback, address {mojo_fn_address}")
prototype = ctypes.CFUNCTYPE(ctypes.c_int)
mojo_func = prototype(mojo_fn_address)
print("calling mojo fn from python")
result = mojo_func()
print(f"result {result}")
--- experiments/widget.mojo ---
import sys
from python import Python
fn main() raises:
var QtWidgets = Python.import_module("PySide6.QtWidgets")
var argv: PythonObject = [sys.argv()[0]]
var app = QtWidgets.QApplication(argv)
var button = QtWidgets.QPushButton("Hello")
button.resize(100, 100)
button.show()
sys.exit(app.exec())
--- experiments/widget.py ---
import sys
from PySide6.QtWidgets import QApplication, QPushButton
if __name__ == "__main__":
app = QApplication(sys.argv)
button = QPushButton("Hello")
button.resize(100, 100)
button.show()
sys.exit(app.exec())
--- experiments/window.mojo ---
import sys
from python import Python
fn main() raises:
var QtGui = Python.import_module("PySide6.QtGui")
var argv: PythonObject = [sys.argv()[0]]
var app = QtGui.QGuiApplication(argv)
var window = QtGui.QWindow()
window.setTitle("Mojo window")
window.resize(100, 100)
window.requestActivate()
window.show()
print("size", window.size(), "active", window.isActive(), "winid", window.winId())
sys.exit(app.exec())
_ = window
--- experiments/window.py ---
import sys
from PySide6.QtGui import QGuiApplication, QWindow
if __name__ == "__main__":
app = QGuiApplication(sys.argv)
window = QWindow()
window.setTitle("Python window")
window.resize(100, 100)
window.requestActivate()
window.show()
print("size", window.size(), "active", window.isActive(), "winid", window.winId())
sys.exit(app.exec())
--- invoke.py ---
import ctypes
from PySide6.QtCore import QObject, Slot
prototype = ctypes.CFUNCTYPE(ctypes.c_void_p)
class Invoke(QObject):
def __init__(self, fn_address):
super().__init__()
self.mojo_fn = prototype(fn_address)
@Slot()
def invoke(self):
self.mojo_fn()
--- qt.mojo ---
import sys
from python import Python
fn on_clicked():
print("mojo on_clicked called from Python")
fn main() raises:
Python.add_to_path("./")
var QtGui = Python.import_module("PySide6.QtGui")
var QtQml = Python.import_module("PySide6.QtQml")
var invoke = Python.import_module("invoke")
var fn_address = UnsafePointer[fn () -> None].address_of(on_clicked).bitcast[Int64]()[0]
var invoke_on_clicked = invoke.Invoke(fn_address)
var argv: PythonObject = [sys.argv()[0]]
var app = QtGui.QGuiApplication(argv)
var engine = QtQml.QQmlApplicationEngine()
engine.rootContext().setContextProperty("on_clicked", invoke_on_clicked)
engine.load("app.qml")
if not engine.rootObjects():
sys.exit(-1)
sys.exit(app.exec())
_ = engine
_ = invoke_on_clicked
--- LICENSE ---
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--- README.md ---
<br/>
<p align="center">
<a href="https://github.com/alainrollejr/mocodes">
<img src="https://github.com/alainrollejr/mocodes/blob/main/mocodeslogo.png" alt="Logo" width="200" height="200">
</a>
<h1 align="center">MoCodes</h1>
<p align="center">
An Error Correction (De)Coding library in pure Mojo 🔥
</p>
</p>
## About The Project
MoCodes is a stand-alone Error Correction (De)Coding framework that leverages the power of Mojo.
As [discussed](https://docs.modular.com/mojo/why-mojo) by Modular, Mojo is a language for the future of AI development. Built on top of MLIR technology, rather than existing GCC and LLVM approaches, Mojo looks and feels like Python code, yet performs much closer to languages like Rust or C++.
Error Correction Codes are being used in domains such as Wireless Communication and Quantum Computing. They are known to be very compute intensive, so much so that until recently they were implemented in dedicated ASIC silicon or programmed on FPGA accelerators.
In recent years with the advent of wide-vector SIMD CPU architectures and affordable yet powerful GPU cores they have been also implemented in C++ with a lot of vendor-specific intrinsics on CPU or with CUDA on GPU as well.
About time then to take a stab at how well Mojo lives up to the challenge (and how well the authors live up to the challenge of understanding how Mojo is meant to be used)
## Benchmark
We've been on a voyage of exploration to find out how platform-independent frameworks originally meant for machine learning can be repurposed for error correction decoding. We have had reasonable results on GPU and TPU but not until Mojo came along we've reached decent throughputs on CPU. Results ofc vary with platform specifics, we have tried Intel, AMD and Macbook M3.
![ldpc_benchmark](https://github.com/alainrollejr/mocodes/blob/main/mocodesbenchmark.png)
While that looks awesome we estimate that there is a performance gap of about a factor 2 yet to be closed wrt C++ code that uses vendor specific intrinsics eg from the avx instruction set on Intel. Game on !
For now we only support generic (ir)regular LDPC codes with *embarrassingly parallel* flooding batch decoding. We have committed just one example (1512 x 1872) LDPC Parity Check Matrix to this repo. This sparse parity check matrix has 7092 non-zero elements and is shown hereafter.
![ldpc_pcm](https://github.com/alainrollejr/mocodes/blob/main/codebook/example_pcm.png)
For now, this parity check matrix gets translated to look-up tables by an offline scipy script that takes an .npz file as input. The look-up tables get stored in the /codebook/ subdirectory.
## Quick Start
Try out the LDPC benchmark for yourself, on your own platform:
```
mojo build ldpcdec.mojo
```
```
./ldpcdec
```
You can tweak the following parameters in the main() function of [types.mojo](https://github.com/alainrollejr/mocodes/blob/main/types.mojo): *intra_codeword_parallellism_factor, ncodewordperthread, nthread*. Currently committed defaults seem to be close to optimal regardless the platform we have tried.
## Roadmap
### v1.0 ✅
- [x] support for irregular LDPC decoding
- [x] support for (batch) early stopping
### v1.1 (WIP)
- [ ] Improve throughput (target: factor 2) by community expertise injection
- [ ] Add a serving functionality (preferably gRPC based, ideally leveraging MAX serving)
- [ ] Add profiling and proper benchmarking tests
### v1.2
- [ ] incorporate generation of Look-Up Tables in the mojo code, such that the .npz file becomes the only configuration input that defines the code
- [ ] add an LDPC encoder
- [ ] add a script to simulate and visualise BER and BLER curves
- [ ] Autotuning and related features
### Longer Term
- [ ] Add polar codes
- [ ] Add Reed-Solomon codes
- [ ] Add CRC check codes
- [ ] Add layered LDPC decoding
## Contributing
The way we set this repo up should allow Mojo experts to contribute without necessarily being Error Correction Coding specialists.
Notably, the LDPC heavy lifting is done by a handful of functions in [types.mojo](https://github.com/alainrollejr/mocodes/blob/main/ldpc/types.mojo), i.e. *fn all_Lqij()* and *fn cnpu()*.
Memory load and store at this point seem to determine the throughput so all tips and tricks to speed up that memory access would much appreciated, along with any other improvements that can be spotted by expert *Mojicans*.
If you are considering larger contributions, feel free to contact us for a smoother communication channel on Discord. If you find a bug or have an idea for a feature, please use our issue tracker. Before creating a new issue, please:
* Check if the issue already exists. If an issue is already reported, you can contribute by commenting on the existing issue.
* If not, create a new issue and include all the necessary details to understand/recreate the problem or feature request.
### Creating A Pull Request
1. Fork the Project
2. Create your Feature Branch
3. Commit your Changes
4. Push to the Branch
5. Open a Pull Request
> Once your changes are pushed, navigate to your fork on GitHub. And create a pull request against the original repository.
> - Before creating a PR make sure the functional text output of ./ldpcdec is the same as the one on the main branch, i.e the batch syndrome on the all-zeros codewords should stay zero and the logit output values should all still equal 127.
> - In the pull request, provide a detailed description of the changes and why they're needed. Link any relevant issues.
## License
Distributed under the Apache 2.0 License.
## Acknowledgements
* Built with [Mojo](https://github.com/modularml/mojo) created by [Modular](https://github.com/modularml)
--- codebook/__init__.mojo ---
--- codebook/luts.mojo ---
alias nnz = 7092
alias nc = 1872
alias cnpu_sizes: VariadicList[Int]=VariadicList (3, 4, 5, 6, 8, 10)
alias ncnpu = 6
alias cnpu_indices: VariadicList[Int]=VariadicList (0, 216, 936, 1260, 1368, 1440)
alias vnpu_sizes: VariadicList[Int]=VariadicList (22, 23, 10, 5, 14, 7, 13, 6, 8, 9, 16, 9, 12, 1)
alias nvnpu = 14
alias vnpu_indices: VariadicList[Int]=VariadicList (0, 36, 72, 108, 180, 216, 252, 288, 324, 360, 396, 432, 468, 504)
--- codebook/repeats.bin ---
--- ldpc/__init__.mojo ---
--- ldpc/types.mojo ---
from math import trunc, mod,min,abs,max
from memory.unsafe import DTypePointer
from sys.info import simdwidthof
from python import Python
from python.object import PythonObject
from random import rand, randint
from algorithm import vectorize, parallelize
from testing import assert_true
from tensor import Tensor, TensorSpec, TensorShape
from sys.intrinsics import strided_load, PrefetchOptions
from sys.info import num_physical_cores, num_logical_cores, num_performance_cores
from collections import List
from collections.vector import InlinedFixedVector
alias dtype = DType.int8
alias nelts = 2*simdwidthof[dtype]() # The SIMD vector width, for some reason overbooking by factor 2 helps
alias max_allowed = SIMD[DType.int16,nelts](127)
alias min_allowed = SIMD[DType.int16,nelts](-127)
@parameter
fn all_cnpu_compiled(inout ip: Tensor3D, nnz: Int, ncnpu: Int, cnpu_sizes: VariadicList[Int],cnpu_indices: VariadicList[Int]) raises:
var slice_start : Int = 0
for idx in range(ncnpu):
var slice_stop : Int
var n = cnpu_sizes[idx]
if (idx == (ncnpu - 1)):
slice_stop = nnz
else:
slice_stop = slice_start + (cnpu_indices[idx+1] - cnpu_indices[idx])*n
var block = ip.get_reference_to_row_slice(slice_start, slice_stop)
# block.print()
# print("cnpu [",slice_start,":",slice_stop,"] reshape to ",n)
block.reshape_dim0(n)
block.cnpu()
block.flatten_dim2()
slice_start = slice_stop
@parameter
fn all_syndromes_compiled(inout ip: Tensor3D,nnz: Int, ncnpu: Int, cnpu_sizes: VariadicList[Int], cnpu_indices: VariadicList[Int]) raises:
var slice_start : Int = 0
for idx in range(ncnpu):
var slice_stop : Int
var n = cnpu_sizes[idx]
if (idx == (ncnpu - 1)):
slice_stop = nnz
else:
slice_stop = slice_start + (cnpu_indices[idx+1] - cnpu_indices[idx])*n
var block = ip.get_reference_to_row_slice(slice_start, slice_stop)
# block.print()
# print("cnpu [",slice_start,":",slice_stop,"] reshape to ",n)
block.reshape_dim0(n)
block.syndromes()
block.flatten_dim2()
slice_start = slice_stop
@parameter
fn all_Lqij(inout ip: Tensor3D, llr: Tensor3D, start_codeword_idx: Int, intra_codeword_parallellism_factor: Int,nc: Int,rep_indices: Tensor[DType.uint16], rep_offsets: Tensor[DType.uint16], r2c_indices: Tensor[DType.uint16]) raises:
# this version just loops over columns of the virtual column-first stored LLRs
# below prefetch lines compile but don't seem to make a performance difference
# alias r_opt = PrefetchOptions().high_locality()
# llr.data().prefetch[r_opt]()
# ip.data().prefetch[r_opt]()
@parameter
fn vnpu(column_idx:Int):
var n_simd = rep_indices[column_idx]
var n = n_simd.to_int()
var slice_start = rep_offsets[column_idx].to_int()
var lut_idx_cache = InlinedFixedVector[Int](n)
for j in range(0,n):
var m = r2c_indices[slice_start + j].to_int()
lut_idx_cache[j] = m
@parameter
fn vp[nelts_local: Int](k: Int):
# if n > 1:
var sum = llr.load[nelts](column_idx, k+start_codeword_idx)
var sum_int16 = sum.cast[DType.int16]()
for j in range(0,n):
var m = lut_idx_cache[j]
var el = ip.load[nelts](m, k)
var el_16 = el.cast[DType.int16]()
sum_int16 += el_16
var tmp = sum_int16
for j in range(n):
# var m = r2c_indices[slice_start+j]
var m = lut_idx_cache[j]
# TODO: find a way to avoid the second load from memory, perhaps by making use of memory > buffer struct
var el = ip.load[nelts](m, k)
tmp = sum_int16 - el.cast[DType.int16]()
tmp = tmp.min(max_allowed)
tmp = tmp.max(min_allowed)
var tmp_dtype = tmp.cast[dtype]()
ip.store[nelts](m,k,tmp_dtype)
vectorize[vp, nelts](ip.dim1)
#vectorize_unroll[nelts,8,vp](ip.dim1) # unroll factor ideally set to ip.dim1//nelts
parallelize[vnpu](nc,intra_codeword_parallellism_factor)
@parameter
fn all_LQ(inout ip: Tensor3D, llr: Tensor3D, inout op: Tensor3D, start_codeword_idx: Int, intra_codeword_parallellism_factor: Int,nc: Int, ncodeword: Int, rep_indices: Tensor[DType.uint16], rep_offsets: Tensor[DType.uint16], r2c_indices: Tensor[DType.uint16]) raises:
@parameter
fn vnpu(codebit_idx:Int): # equivalent of : "for codebit_idx in range(nc):"
var n = rep_indices[codebit_idx].to_int()
var slice_start = rep_offsets[codebit_idx].to_int()
var lut_idx_cache = InlinedFixedVector[Int](n)
for j in range(0,n):
var m = r2c_indices[slice_start+j].to_int()
lut_idx_cache[j] = m
@parameter
fn vp[nelts_local: Int](k: Int): # equivalent of : "for k in range(ncodeword):"" but we are taking nelts = simdwidth codewords at a time
var sum = llr.load[nelts](codebit_idx, k+start_codeword_idx)
var tmp = sum.cast[DType.int16]()
for j in range(0,n):
var m = lut_idx_cache[j]
var el = ip.load[nelts](m, k)
tmp += el.cast[DType.int16]()
tmp = tmp.min(max_allowed)
tmp = tmp.max(min_allowed)
var tmp_dtype = tmp.cast[dtype]()
@unroll
for j in range(nelts): # subtoptimal, should be strided store but syntax eludes me a bit
op.store[1](start_codeword_idx+k+j,codebit_idx,tmp_dtype[j])
vectorize[vp, nelts](ncodeword)
#vectorize_unroll[nelts,8,vp](ip.dim1) # unroll factor ideally set to ip.dim1//nelts
parallelize[vnpu](nc,intra_codeword_parallellism_factor)
@parameter
fn all_LQ_for_syndrome(inout ip: Tensor3D, llr: Tensor3D, inout op: Tensor3D, start_codeword_idx: Int, intra_codeword_parallellism_factor: Int,nc: Int, rep_indices:Tensor[DType.uint16], rep_offsets: Tensor[DType.uint16], r2c_indices: Tensor[DType.uint16]) raises:
@parameter
fn vnpu(column_idx:Int): # equivalent of : "for column_idx in range(nc):"
var n = rep_indices[column_idx].to_int()
var slice_start = rep_offsets[column_idx].to_int()
var lut_idx_cache = InlinedFixedVector[Int](n)
for j in range(0,n):
var m = r2c_indices[slice_start+j].to_int()
lut_idx_cache[j] = m
@parameter
fn vp[nelts_local: Int](k: Int):
# TODO: if n == 1 we can at once set the result to zero across the board
# also TODO : don't load the same values twice, create a local array of SIMD for the n values
var sum = llr.load[nelts](column_idx, k+start_codeword_idx)
var sum_int16 = sum.cast[DType.int16]()
for j in range(0,n):
var m = lut_idx_cache[j]
var el = ip.load[nelts](m, k)
sum_int16 += el.cast[DType.int16]()
var tmp = sum_int16
for j in range(n):
var m = lut_idx_cache[j]
tmp = tmp.min(max_allowed)
tmp = tmp.max(min_allowed)
var tmp_dtype = tmp.cast[dtype]()
op.store[nelts](m,k,tmp_dtype)
vectorize[vp, nelts](ip.dim1)
parallelize[vnpu](nc,intra_codeword_parallellism_factor)
@parameter
fn decode_compiled_v5[ base_niter: Int, max_niter: Int](ip : Tensor3D, inout op : Tensor3D, inout batch_syndrome: Int, intra_codeword_parallellism_factor: Int, start_codeword_idx: Int, nc: Int,nnz: Int, ncnpu: Int, nvnpu: Int, ncodeword: Int, rep_indices: Tensor[DType.uint16], rep_offsets: Tensor[DType.uint16], c2r_indices: Tensor[DType.uint16], r2c_indices: Tensor[DType.uint16], vnpu_sizes: VariadicList[Int], vnpu_indices: VariadicList[Int], cnpu_sizes: VariadicList[Int], cnpu_indices: VariadicList[Int]) raises:
#print("decode_compiled_v5 on start_codeword_idx = ",start_codeword_idx)
var ip_llr_rep = repeat_compiled_offset(ip, start_codeword_idx,rep_indices, nnz, ncodeword)
ip_llr_rep.set_num_workers(intra_codeword_parallellism_factor)
var syndrome_scratchpad = Tensor3D(nnz, ncodeword)
syndrome_scratchpad.set_num_workers(intra_codeword_parallellism_factor)
# first iteration, declares the variables
var reliabilities = c2r(ip_llr_rep,c2r_indices) # a permuted copy # ip_llr_rep_rfirst
reliabilities.set_num_workers(intra_codeword_parallellism_factor)
all_cnpu_compiled(reliabilities,nnz, ncnpu, cnpu_sizes,cnpu_indices) # modifies in-place
all_Lqij(reliabilities, ip,start_codeword_idx,intra_codeword_parallellism_factor,nc,rep_indices,rep_offsets,r2c_indices) # modifies in-place
# remaining iterations
#@unroll
for idx in range(1,base_niter-1):
all_cnpu_compiled(reliabilities,nnz, ncnpu, cnpu_sizes,cnpu_indices) # modifies in-place
all_Lqij(reliabilities, ip,start_codeword_idx,intra_codeword_parallellism_factor,nc,rep_indices,rep_offsets,r2c_indices) # modifies in-place
# final iteration
all_cnpu_compiled(reliabilities,nnz, ncnpu, cnpu_sizes,cnpu_indices) # modifies in-place
all_LQ(reliabilities, ip, op, start_codeword_idx, intra_codeword_parallellism_factor,nc,ncodeword,rep_indices,rep_offsets,r2c_indices) # modifies in-place
# batch syndrome computation (inefficient, but leaves reliabilities untouched for continued iteration if must be )
all_LQ_for_syndrome(reliabilities, ip, syndrome_scratchpad, start_codeword_idx,intra_codeword_parallellism_factor,nc,rep_indices,rep_offsets,r2 |
README.md exists but content is empty.
- Downloads last month
- 33